-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTargetSum.cpp
More file actions
61 lines (51 loc) · 1021 Bytes
/
TargetSum.cpp
File metadata and controls
61 lines (51 loc) · 1021 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<bits/stdc++.h>
using namespace std;
int CountSubsetSum(int arr[], int n, int s1)
{
int dp[n+1][s1+1];
for(int i=0;i<n+1;i++)
{
for(int j=0;j<s1+1;j++)
{
if(i==0)
{
dp[i][j] = 0;
}
if(j==0)
{
dp[i][j] = 1;
}
}
}
for(int i=1;i<n+1;i++)
{
for(int j=1;j<s1+1;j++)
{
if(arr[i-1]<=j)
{
dp[i][j] = dp[i-1][j-arr[i-1]]+dp[i-1][j];
} else {
dp[i][j] = dp[i-1][j];
}
}
}
return dp[n][s1];
}
int TargetSum(int arr[], int n, int diff)
{
int sum=0;
for(int i=0;i<n;i++)
{
sum+=arr[i];
}
int s1 = (diff+sum)/2;
return CountSubsetSum(arr, n, s1);
}
int main() {
int n=4,diff=1;
int arr[n] = {1, 1, 2, 3};
cout<<TargetSum(arr, n, diff);
}
//Its solution is as same as CountNoOfSubsetWithGivenDiff
//output
//3