Skip to content

Commit 784046d

Browse files
authored
Merge pull request #40 from vipu18/patch-2
Implement subset sum problem using dynamic programming
2 parents 1277d83 + 87421da commit 784046d

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

0 commit comments

Comments
 (0)