-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path051_Return Subsets Sum to K.cpp
71 lines (51 loc) · 1.2 KB
/
051_Return Subsets Sum to K.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// TC -> O(2^n)
// SC -> O(n * (2^n))
void helper(int idx, int sum, int n, vector<int> ds, vector<int>& arr, vector<vector<int>>& ans, int k)
{
if(idx == n)
{
if(sum == k)
{
ans.push_back(ds);
}
return;
}
ds.push_back(arr[idx]);
sum += arr[idx];
helper(idx+1, sum, n, ds, arr, ans, k);
ds.pop_back();
sum -= arr[idx];
helper(idx+1, sum, n, ds, arr, ans, k);
}
vector<vector<int>> findSubsetsThatSumToK(vector<int> arr, int n, int k)
{
// Write your code here.
vector<vector<int>> ans;
vector<int> ds;
helper(0, 0, n, ds, arr, ans, k);
return ans;
}
// TC -> O(n * (2^n))
// SC -> O(n * (2^n))
vector<vector<int>> findSubsetsThatSumToK(vector<int> arr, int n, int k)
{
// Write your code here.
int range = 1 << n;
vector<vector<int>> ans;
for(int mask = 0; mask < range; ++mask)
{
vector<int> ds;
int sum = 0;
for(int i = 0; i < n; ++i)
{
if(mask & (1 << i))
{
sum += arr[i];
ds.push_back(arr[i]);
}
}
if(sum == k)
ans.push_back(ds);
}
return ans;
}