-
Notifications
You must be signed in to change notification settings - Fork 985
/
Copy pathtarget_sum.cpp
38 lines (30 loc) · 979 Bytes
/
target_sum.cpp
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
37
38
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int s = 0;
for(auto x : nums)
s += x;
//count number of subsets with sum as their summation
if(s < target || (target + s)&1 )
return 0;
int n = nums.size();
int sum = (abs(target) + s)/2;
int dp[n+1][sum+1];
for(int i=0;i<=n;i++)
for(int j=0;j<=sum;j++)
{
if(i == 0 && j == 0)
dp[i][j] = 1;
else if(i == 0)
dp[i][j] = 0;
else if(j < nums[i-1])
dp[i][j] = dp[i-1][j];
else
dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i-1]];
}
return dp[n][sum];
}
};
/*
this problem is similar of just same as the SUBSET SUM PROBLEM
*/