Skip to content

Commit 0af99eb

Browse files
authored
416. Partition Equal Subset sum
1 parent ffdb3dc commit 0af99eb

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Dynamic-Programming/canPartition.cpp

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public:
3+
bool canPartition(vector<int>& nums) {
4+
int count = 0;
5+
for(int i = 0; i < nums.size(); ++i) {
6+
count+=nums[i];
7+
}
8+
if (count%2!=0) return false;
9+
int halfSum = count/2;
10+
int n = nums.size();
11+
12+
bool dp[n+1][halfSum+1];
13+
int i;
14+
for(i = 0 ; i <=halfSum; ++i) {
15+
dp[0][i] = false;
16+
}
17+
for(i = 0 ; i <= n; ++i) {
18+
dp[i][0] = true;
19+
}
20+
for(i = 1; i <= n; ++i) {
21+
for(int j = 1; j <= halfSum; ++j) {
22+
if(nums[i-1] <= j) {
23+
dp[i][j] = dp[i-1][j - nums[i-1]] || dp[i-1][j];
24+
} else {
25+
dp[i][j] = dp[i-1][j];
26+
}
27+
}
28+
}
29+
return dp[n][halfSum];
30+
31+
}
32+
};

0 commit comments

Comments
 (0)