Skip to content

Commit 34c324f

Browse files
Sync LeetCode submission Runtime - 51 ms (91.86%), Memory - 16.8 MB (71.94%)
1 parent 0846b23 commit 34c324f

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> nums = [1,5,11,5]
8+
<strong>Output:</strong> true
9+
<strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11].
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> nums = [1,2,3,5]
16+
<strong>Output:</strong> false
17+
<strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets.
18+
</pre>
19+
20+
<p>&nbsp;</p>
21+
<p><strong>Constraints:</strong></p>
22+
23+
<ul>
24+
<li><code>1 &lt;= nums.length &lt;= 200</code></li>
25+
<li><code>1 &lt;= nums[i] &lt;= 100</code></li>
26+
</ul>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public:
3+
bool canPartition(vector<int>& nums) {
4+
int n = nums.size();
5+
int m = accumulate(nums.begin(), nums.end(), 0);
6+
if (m%2) return false;
7+
vector<bool> dp(m/2+1, false);
8+
dp[0] = true;
9+
if (nums[0] <= m/2) dp[nums[0]] = true;
10+
for (int i=1; i<n; i++) {
11+
vector<bool> newDp = dp;
12+
newDp[nums[i]] = true;
13+
for (int j=0; j<=m/2; j++) {
14+
if (!dp[j] || nums[i] + j > m/2) continue;
15+
newDp[nums[i] + j] = true;
16+
}
17+
dp = newDp;
18+
}
19+
return dp[m/2];
20+
}
21+
};

0 commit comments

Comments
 (0)