Skip to content

Commit 94d4163

Browse files
Create subsetSumDP.cpp
1 parent 0a3c7a6 commit 94d4163

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

subsetSumDP.cpp

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
5+
bool isSubSetSumRecursiveHelper(vector<int> v, int target, int n) {
6+
if(n <= 0 || target < 0) return false;
7+
if(target == 0) return true;
8+
9+
bool include = isSubSetSumRecursiveHelper(v, target - v[n], n - 1);
10+
bool exclude = isSubSetSumRecursiveHelper(v, target, n - 1);
11+
return include || exclude;
12+
}
13+
14+
15+
bool isSubSetSumRecursive(vector<int> v, int target) {
16+
if(v.size() == 0) return false;
17+
18+
//pick last element or dont pick;
19+
return isSubSetSumRecursiveHelper(v, target, v.size() - 1);
20+
21+
}
22+
23+
24+
25+
unordered_map<string, int> mp;
26+
bool isSubsetSumMemoizedHelper(vector<int> v, int target, int n) {
27+
28+
if(n <= 0 || target < 0) return false;
29+
30+
if(target == 0) return true;
31+
32+
string key = to_string(n) + '|' + to_string(target);
33+
if(mp.find(key) == mp.end()) {
34+
bool include = isSubsetSumMemoizedHelper(v, target - v[n], n - 1);
35+
bool exclude = isSubsetSumMemoizedHelper(v, target, n - 1);
36+
mp[key] = target;
37+
38+
return include || exclude;
39+
}
40+
//else already found;
41+
return mp[key];
42+
}
43+
44+
45+
bool isSubsetSumMemoized(vector<int> v, int target) {
46+
if(v.size() == 0) return false;
47+
return isSubsetSumMemoizedHelper(v, target, v.size() - 1);
48+
}
49+
50+
51+
bool isSubsetSumDP(vector<int> v, int target) {
52+
if(v.size() == 0) return false;
53+
54+
int n = v.size();
55+
int dp[n + 1][target + 1];
56+
57+
for(int i=0; i<=n; i++) {
58+
dp[0][i] = false;
59+
}
60+
61+
for(int j=0; j<=target; j++) {
62+
dp[j][0] = true;
63+
}
64+
65+
66+
for(int i=1; i<=n; i++) {
67+
for(int j=1; j<=target; j++) {
68+
69+
if(v[i-1] > j) {
70+
dp[i][j] = dp[i-1][j];
71+
}
72+
else {
73+
//include || exclude
74+
dp[i][j] = dp[i-1][j] || dp[i-1][j - v[i-1]];
75+
}
76+
}
77+
}
78+
79+
return dp[n][target];
80+
}
81+
82+
int main() {
83+
cout<<isSubSetSumRecursive({1,2,3,4,5,6,7,8}, 7);
84+
85+
cout<<isSubsetSumMemoized({1,2,3,4,5,6,7,8}, 7);
86+
87+
cout<<isSubsetSumDP({1,2,3,4,5,6,7,8}, 7);
88+
}

0 commit comments

Comments
 (0)