File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include < iostream>
2+ #include < vector>
3+ using namespace std ;
4+
5+ // Paste your Solution class here (choose one implementation)
6+ class Solution {
7+ int mod = 1000000007 ;
8+ public:
9+ int perfectSum (vector<int >& arr, int k) {
10+ int n = arr.size ();
11+ vector<int >prev (k+1 , 0 );
12+ vector<int >curr (k+1 , 0 );
13+ curr[0 ] = 1 ;
14+ prev[0 ] = 1 ;
15+ if (arr[0 ]<=k){
16+ prev[arr[0 ]] = 1 ;
17+ }
18+ for (int i = 1 ; i<n; i++){
19+ for (int tar = 1 ; tar<=k; tar++){
20+ int notTaken = prev[tar];
21+ int take = 0 ;
22+ if (arr[i]<=tar){
23+ take = prev[tar-arr[i]] % mod;
24+ }
25+ curr[tar] = (notTaken+take) % mod;
26+ }
27+ prev = curr;
28+ }
29+ return prev[k];
30+ }
31+ };
32+
33+ int main () {
34+ int n, k;
35+ cout << " Enter number of elements and target sum: " ;
36+ cin >> n >> k;
37+ vector<int > arr (n);
38+ cout << " Enter array elements: " ;
39+ for (int i=0 ; i<n; ++i) cin >> arr[i];
40+
41+ Solution sol;
42+ int result = sol.perfectSum (arr, k);
43+ cout << " Number of subsets with sum " << k << " : " << result << endl;
44+ return 0 ;
45+ }
You can’t perform that action at this time.
0 commit comments