-
Notifications
You must be signed in to change notification settings - Fork 17
/
subset.cpp
37 lines (33 loc) · 871 Bytes
/
subset.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
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
void subsetSumsHelper(int ind, vector < int > & arr, int n, vector < int > & ans, int sum) {
if (ind == n) {
ans.push_back(sum);
return;
}
//element is picked
subsetSumsHelper(ind + 1, arr, n, ans, sum + arr[ind]);
//element is not picked
subsetSumsHelper(ind + 1, arr, n, ans, sum);
}
vector < int > subsetSums(vector < int > arr, int n) {
vector < int > ans;
subsetSumsHelper(0, arr, n, ans, 0);
sort(ans.begin(), ans.end());
return ans;
}
};
int main() {
vector < int > arr{3,1,2};
Solution ob;
vector < int > ans = ob.subsetSums(arr, arr.size());
sort(ans.begin(), ans.end());
cout<<"The sum of each subset is "<<endl;
for (auto sum: ans) {
cout << sum << " ";
}
cout << endl;
return 0;
}