-
Notifications
You must be signed in to change notification settings - Fork 2
/
subsets.cc
67 lines (61 loc) · 1.52 KB
/
subsets.cc
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
// Given a set of distinct integers, S, return all possible subsets.
//
// Note:
// Elements in a subset must be in non-descending order.
// The solution set must not contain duplicate subsets.
// For example,
// If S = [1,2,3], a solution is:
//
// [
// [3],
// [1],
// [2],
// [1,2,3],
// [1,3],
// [2,3],
// [1,2],
// []
// ]
/**
* I will add more solutions later.
*/
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end());
vector<vector<int> > result;
result.push_back(vector<int>());
int size = S.size();
for (int i = 0; i < S.size(); i++) {
int size = result.size();
for (int j = 0; j < size; j++) {
vector<int> temp = result[j];
temp.push_back(S[i]);
result.push_back(temp);
}
}
return result;
}
};
/**
* Here is the dfs solution.
*/
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end());
vector<int> buffer;
vector<vector<int> > result;
dfs(0, S, result, buffer);
result.push_back(buffer);
return result;
}
void dfs(int index, vector<int> &S, vector<vector<int> > &result, vector<int> &buffer) {
for (int i = index; i < S.size(); i++) {
buffer.push_back(S[i]);
result.push_back(buffer);
dfs(i+1, S, result, buffer);
buffer.pop_back();
}
}
};