-
Notifications
You must be signed in to change notification settings - Fork 0
/
09.Count of Subset with given sum.cpp
111 lines (71 loc) · 1.79 KB
/
09.Count of Subset with given 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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//GFG Problem Link : https://practice.geeksforgeeks.org/problems/perfect-sum-problem5633/1
// Error: Code not accepted
// Progress --> pending ( not accepted ) .....->>
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// int solve(int arr[],int n,int sum ,int &count){
// if(sum==0){
// return 1;
// }
// if(n==0){
// return sum==0?1:0;
// }
// if(arr[n-1]<=sum){
// int a= solve(arr,n-1,sum-arr[n-1],count);
// int b= solve(arr,n-1,sum,count);
// return a+b;
// }
// else{
// return solve(arr,n-1,sum,count);
// }
// }
// using memoization \
int solve(int arr[],int sum, int n, vector<vector<int>> &t){
if(sum==0){
return 1;
}
if(n==0){
return sum==0?1:0;
}
if(t[n][sum]!=-1){
return t[n][sum];
}
if(arr[n-1]<=sum){
return t[n][sum]=solve(arr,sum-arr[n-1],n-1,t) + solve(arr,sum,n-1,t);
}
else{
return t[n][sum]=solve(arr,sum,n-1,t);
}
return t[n][sum];
}
int perfectSum(int arr[], int n, int sum)
{
// Your code goes here
vector<vector<int>> t(n+1,vector<int> (sum+1,-1));
int ans =0;int count=0;
count=solve(arr,sum,n,t);
return count;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int n, sum;
cin >> n >> sum;
int a[n];
for(int i = 0; i < n; i++)
cin >> a[i];
Solution ob;
cout << ob.perfectSum(a, n, sum) << "\n";
}
return 0;
}
// } Driver Code Ends