Skip to content

Commit 51b3b9b

Browse files
authored
Create target-sum.cpp
1 parent 980df67 commit 51b3b9b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

C++/target-sum.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Time: O(n * S)
2+
// Space: O(S)
3+
4+
class Solution {
5+
public:
6+
int findTargetSumWays(vector<int>& nums, int S) {
7+
// sum(P) - sum(N) = S
8+
// <=>
9+
// 2 * sum(P) = S + sum(nums)
10+
int sum = accumulate(nums.begin(), nums.end(), 0);
11+
if (sum < S || (S + sum) % 2) {
12+
return 0;
13+
}
14+
return subsetSum(nums, (S + sum) / 2);
15+
}
16+
17+
private:
18+
int subsetSum(vector<int>& nums, int S) {
19+
vector<int> dp(S + 1);
20+
dp[0] = 1;
21+
for (const auto& n : nums) {
22+
for (int i = S; i >= n; --i) {
23+
dp[i] += dp[i - n];
24+
}
25+
}
26+
return dp.back();
27+
}
28+
};

0 commit comments

Comments
 (0)