-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanPartition.cpp
More file actions
29 lines (27 loc) · 853 Bytes
/
canPartition.cpp
File metadata and controls
29 lines (27 loc) · 853 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
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = accumulate(nums.begin(), nums.end(), 0), target = sum >> 1;
if (sum & 1) return false;
vector<bool> dp(target + 1, 0);
dp[0] = true;
for(auto num : nums)
for(int i = target; i >= num; i--)
dp[i] = dp[i] || dp[i - num];
return dp[target];
}
};
class Solution {
public:
bool canPartition(vector<int>& nums) {
const int MAX_NUM = 100;
const int MAX_ARRAY_SIZE = 200;
bitset<MAX_NUM * MAX_ARRAY_SIZE / 2 + 1> bits(1);
int sum = 0;
for (auto n : nums) {
sum += n;
bits |= bits << n; //moving everybit to left n bits means all possible pre sum has been added with n
}
return !(sum % 2) && bits[sum / 2];
}
};