zoukankan      html  css  js  c++  java
  • Subsets

    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先排序下,使全集能够按顺序输出。
    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

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

      

  • 相关阅读:
    无锁队列的实现
    C/C++语言中闭包的探究及比较
    Linus:利用二级指针删除单向链表
    Unix考古记:一个“遗失”的shell
    “C++的数组不支持多态”?
    Alan Cox:单向链表中prev指针的妙用
    二叉树迭代器算法
    C语言全局变量那些事儿
    数据即代码:元驱动编程
    C++模板”>>”编译问题与词法消歧设计
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3599862.html
Copyright © 2011-2022 走看看