Skip to content

Commit 38d2995

Browse files
committed
494. Target Sum
1 parent 42cee7e commit 38d2995

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

target-sum.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Runtime: 4 ms
2+
// Memory Usage: 8.7 MB
3+
class Solution {
4+
public:
5+
int findTargetSumWays(vector<int>& nums, int S) {
6+
int sum = accumulate(nums.begin(), nums.end(), 0);
7+
8+
if (sum < S || S < -sum || (sum + S) % 2 == 1)
9+
return 0;
10+
11+
int target = (sum + S) >> 1;
12+
13+
vector<int> dp(target + 1, 0);
14+
dp[0] = 1;
15+
16+
for (int a : nums) {
17+
for (int s = target; s >= a; s--) {
18+
dp[s] += dp[s - a];
19+
}
20+
}
21+
return dp[target];
22+
}
23+
};

0 commit comments

Comments
 (0)