-
Notifications
You must be signed in to change notification settings - Fork 985
/
Copy pathCountSubsetsWithGivenSum.cpp
74 lines (54 loc) · 1.39 KB
/
CountSubsetsWithGivenSum.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<bits/stdc++.h>
using namespace std;
// Question
// Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X.
//This is a dp problem
// Time Complexity: O(sum*n), where the sum is the ‘target sum’ and ‘n’ is the size of the array.
// Auxiliary Space: O(sum*n), as the size of the 2-D array, is sum*n.
int totalSubsets(int a[],int n,int tar)
{
// Initializing the matrix
int dp[n + 1][tar + 1];
// Initializing the first value of matrix
dp[0][0] = 1;
for (int i = 1; i <= tar; i++)
dp[0][i] = 0;
for (int i = 1; i <= n; i++)
dp[i][0] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= tar; j++)
{
// if the value is greater than the sum
if (a[i - 1] <= j)
{
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - a[i - 1]];
}
else
{
dp[i][j] = dp[i - 1][j];
}
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=tar;j++)
{
cout<<dp[i][j]<<" ";
}
cout<<"\n";
}
return dp[n][tar];
}
int main()
{
int n,tar;
cin>>n>>tar;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int val =totalSubsets(a,n,tar);
cout<<"Total subsets are : "<<val<<"\n";
}