Skip to content

Commit 9f2b80b

Browse files
authored
Create partition-equal-subset-sum.cpp
1 parent ded44ce commit 9f2b80b

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

C++/partition-equal-subset-sum.cpp

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n * s), s is the sum of nums.
2+
// Space: O(s)
3+
4+
class Solution {
5+
public:
6+
bool canPartition(vector<int>& nums) {
7+
const auto sum = accumulate(nums.cbegin(), nums.cend(), 0);
8+
if (sum % 2) {
9+
return false;
10+
}
11+
12+
vector<bool> dp(sum / 2 + 1);
13+
dp[0] = true;
14+
for (const auto& num : nums) {
15+
for (int i = 1; i < dp.size(); ++i) {
16+
if (num <= i) {
17+
dp[i] = dp[i] || dp[i - num];
18+
}
19+
}
20+
}
21+
return dp.back();
22+
}
23+
};

0 commit comments

Comments
 (0)