-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathSubsets.cpp
45 lines (42 loc) · 1.32 KB
/
Subsets.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
class Solution {
public:
void subsetsUtils(int idx, vector<int> &S, vector<int> &solution, vector<vector<int> > &result) {
result.push_back(solution);
if(idx == S.size()) {
return;
}
for(int i = idx; i < S.size(); ++i) {
solution.push_back(S[i]);
subsetsUtils(i + 1, S, solution, result);
solution.pop_back();
}
}
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > result;
vector<int> solution;
if(S.size() < 0) return result;
subsetsUtils(0, S, solution, result);
return result;
}
};
// Alternatives
class Solution {
public:
void subsetsUtils(int idx, vector<int> &S, vector<int> &solution, vector<vector<int> > &result) {
if(idx == S.size()) {
result.push_back(solution);
return;
}
solution.push_back(S[idx]);
subsetsUtils(idx + 1, S, solution, result);
solution.pop_back();
subsetsUtils(idx + 1, S, solution, result);
}
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > result;
vector<int> solution;
if(S.size() < 0) return result;
subsetsUtils(0, S, solution, result);
return result;
}
};