You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
5
+
> Given an integer array `nums`, return `true` if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or `false` otherwise.
6
6
7
7
```
8
8
Example 1:
@@ -90,12 +90,12 @@ These five steps are a pattern for solving `Dynamic Programming` problems.
90
90
# 5 T T F F F T T F F F T T # dp
91
91
```
92
92
* After analyzing the sample `dp` grid, we can derive the `Recurrence Formula`:
93
-
```python
94
-
dp[j] = dp[j] or dp[j - nums[i]]
93
+
```cpp
94
+
dp[j] = dp[j] || dp[j - nums[i]]
95
95
```
96
96
4. Determine the `dp` array's traversal order
97
97
*`dp[j]` depends on `dp[j]` and `dp[j - nums[i]]`, so we should traverse the `dp` array from top to bottom, then **from right to left**.
98
-
* Please think if we can traverse the `dp` array from top to bottom, then `from left to right`? In the `Python` code comments, I will answer this question.
98
+
* Please think if we can traverse the `dp` array from top to bottom, then `from left to right`? In the `Python`solution's code comments, I will answer this question.
99
99
5. Check the `dp` array's value
100
100
* Print the `dp` to see if it is as expected.
101
101
@@ -108,15 +108,16 @@ These five steps are a pattern for solving `Dynamic Programming` problems.
108
108
classSolution:
109
109
defcanPartition(self, nums: List[int]) -> bool:
110
110
sum_ =sum(nums)
111
+
111
112
if sum_ %2==1:
112
113
returnFalse
113
-
114
+
114
115
dp = [False] * ((sum_ //2) +1)
115
116
dp[0] =True
116
-
117
+
117
118
for num in nums:
118
-
# If traverse from left to right, the newly assigned value `dp[j - num]` will affect the subsequent `dp[j]`.
119
-
#Then it would be wrong because each `num` can only be used once.
119
+
# If traversing from left to right, the newly assigned value `dp[j]` will act as `dp[j - num]` later,
120
+
#then the subsequent `dp[j]` will be affected. But each `num` can only be used once.
0 commit comments