-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubsetSums.cpp
More file actions
31 lines (28 loc) · 977 Bytes
/
subsetSums.cpp
File metadata and controls
31 lines (28 loc) · 977 Bytes
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
/*Given a list(Arr) of N integers, print sums of all subsets in it. Output should be printed in increasing order of sums.
Example 1:
Input:N = 2
Arr = [2, 3]
Output:
0 2 3 5
Explanation:
When no elements is taken then Sum = 0.When only 2 is taken then Sum = 2.When only 3 is taken then Sum = 3.When element 2 and 3 are taken then
Sum = 2+3 = 5. */
public:
void func(int ind, int sum,vector<int> &arr, int N, vector<int> &sumSubset) {
if(ind == N) {
sumSubset.push_back(sum);
return;
}
// pick the element
func(ind + 1, sum + arr[ind], arr, N, sumSubset);
// Do-not pick the element
func(ind + 1, sum, arr, N, sumSubset);
}
public:
vector<int> subsetSums(vector<int> arr, int N)
{
vector<int> sumSubset;
func(0, 0, arr, N, sumSubset);
sort(sumSubset.begin(), sumSubset.end());
return sumSubset;
}