-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLeetcode-subset_sum.cpp
More file actions
36 lines (35 loc) · 929 Bytes
/
Leetcode-subset_sum.cpp
File metadata and controls
36 lines (35 loc) · 929 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
* Problem link : https://leetcode.com/problems/partition-equal-subset-sum/
*
*/
class Solution {
public:
bool canPartition(vector<int>& nums) {
int n = nums.size();
int sum = 0;
for (int x : nums) {
sum += x;
}
if (sum % 2) {
return false;
}
bool dp[n+1][sum+1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
if (j == 0) {
dp[i][j] = true;
} else if (i == 0) {
dp[i][j] = false;
} else if (j - nums[i-1] < 0){
dp[i][j] = dp[i-1][j];
} else {
dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i-1]];
}
if (j == sum/2 && dp[i][j]) {
return true;
}
}
}
return false;
}
};