首页 > 其他 > 详细

Subsets

时间:2014-03-14 17:48:50      阅读:397      评论:0      收藏:0      [点我收藏+]

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],
  []
]

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;
    }
};

  

Subsets,布布扣,bubuko.com

Subsets

原文:http://www.cnblogs.com/pengyu2003/p/3599862.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!