Skip to content

Commit 1d7159d

Browse files
authored
Count number of subset with a given difference.cpp
1 parent ce750fe commit 1d7159d

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/* Count the number of subset with a given difference - Top Down Approach*/
2+
3+
/*Let sum of subset 1 be s1 and subset 2 with s2
4+
s1 - s2 = diff (given)
5+
s1 + s2=sum of array (logical)
6+
Therefore adding both eq we get :
7+
2s1= diff + sum of array
8+
s1= (diff + sum of array)/2;
9+
Problem reduces to find no of subsets with given sum*/
10+
11+
#include <bits/stdc++.h>
12+
using namespace std;
13+
#define int long long int
14+
#define fast \
15+
cin.sync_with_stdio(false); \
16+
cin.tie(NULL); \
17+
cout.tie(NULL);
18+
19+
int dp[1001][10001];
20+
int CountOfSubsetSumGivenDiff(int n, int arr[], int sum)
21+
{
22+
for (int i = 0; i <= n; i++)
23+
dp[i][0] = 1;
24+
for (int i = 1; i <= sum; i++)
25+
dp[0][i] = 0;
26+
for (int i = 1; i <= n; i++)
27+
{
28+
for (int j = 1; j <= sum; j++)
29+
{
30+
if (arr[i - 1] <= j)
31+
dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j];
32+
else
33+
dp[i][j] = dp[i - 1][j];
34+
}
35+
}
36+
return dp[n][sum];
37+
}
38+
signed main()
39+
{
40+
fast;
41+
int n = 4;
42+
int arr[4] = {1, 2, 3, 3};
43+
int diff = 1;
44+
int sum = accumulate(arr, arr + n, 0);
45+
int s1 = (diff + sum) / 2;
46+
//memonization
47+
memset(dp, -1, sizeof(dp));
48+
49+
cout << CountOfSubsetSumGivenDiff(n, arr, s1);
50+
51+
return 0;
52+
}

0 commit comments

Comments
 (0)