Given a set of distinct integers, S, return all possible subsets.
Note:
For
example,
If S = [1,2,3],
a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
S先排序下,使全集能够按顺序输出。
|
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 |
class
Solution {public: vector<vector<int> >re; vector<vector<int> > subsets(vector<int> &S) { sort(S.begin(),S.end()); for(int
i = 0 ; i <= S.size() ; i++) { find(S , i); } return
re; } void
find(vector<int> ve,int
k) { vector<int> result; if(k == 0) { re.push_back(result); return; } if(k == ve.size()) { re.push_back(ve); return; } get(ve,-1,k,result); } void
get(vector<int> ve,int
begin,int
k,vector<int> result) { if(begin >= 0) { result.push_back(ve[begin]); } if(k == 0) { sort(result.begin(),result.end()); re.push_back(result); return; } for(int
i = begin+1; i <= ve.size() - k ; i++) { get(ve,i,k-1,result); } }}; |
有更简单的做法,维护一个index。当index到尾部是则将集合返回。
看到一个更漂亮的做法,忍不住贴过来。源自http://www.cppblog.com/Uriel/articles/205467.html
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
class
Solution {public: vector<vector<int> > subsets(vector<int> &S) { vector<vector<int> > res; sort(S.begin(), S.end()); for(int
i = 0; i < (1 << S.size()); ++i) { vector<int> tp; for(int
j = 0; j < S.size(); ++j) { if((1 << j) & i) tp.push_back(S[j]); } res.push_back(tp); } return
res; }}; |
原文:http://www.cnblogs.com/pengyu2003/p/3599862.html