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

      

  • 相关阅读:
    java过滤器 Fliter
    input标签name、value与id属性
    python 简单的数据库操作之转账
    正则表达式基本语法
    适合新手的Python爬虫小程序
    如何使用EditPlus将json格式字符串默认为UTF-8格式
    codeforces 527C:STL set
    codeforces 527B:瞎搞
    HDU 3397 线段树
    HDU 3436:splay tree
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3599862.html
Copyright © 2011-2022 走看看