码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode || 78、Subsets

时间:2015-04-10 11:35:42      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:leetcode   dfs   集合   子集   回溯法   

problem:

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

Hide Tags
 Array Backtracking Bit Manipulation
题意:给定一个数组,求出其所有的子集,包括空集

thinking:

(1)77题中已经使用DFS求出数组的指定个数为K的所有子集,这里K的取值范围为1~n,n为数组长度

具体参考:http://blog.csdn.net/hustyangju/article/details/44974825

code:

class Solution {
private:
    vector<vector<int> > ret;
    vector<int> tmp;
public:
    vector<vector<int> > subsets(vector<int> &S) {
    ret.clear();
    unsigned int n=S.size();
    if(n==0)
        return ret;
    sort(S.begin(),S.end());
    tmp.clear();
    ret.push_back(tmp);
    for(int k=1;k<=n;k++)
    {
        tmp.resize(k);
        dfs(0,n,S,k,0);
    }
    return ret;
    }
protected:
    void dfs(int dep, int n, vector<int> &S,int k,int start)
    {
       if(dep==k)
       {
           ret.push_back(tmp);
           return;
       }
       for(int i=start;i<n;i++)
       {
           tmp[dep]=S[i];
           dfs(dep+1,n,S,k,i+1);
       }
    }
};

另一种DFS法:

class Solution {
private:
    vector<vector<int> > ret;
public:
    void dfs(int dep, int maxDep, vector<int> &num, vector<int> a, int start)
    {
        ret.push_back(a);
        
        if (dep == maxDep)
            return;
            
        for(int i = start; i < num.size(); i++)
        {
            vector<int> b(a);
            b.push_back(num[i]);
            dfs(dep + 1, maxDep, num, b, i + 1);
        }
    }
    
    vector<vector<int> > subsets(vector<int> &S) {
        sort(S.begin(), S.end());
        ret.clear();
        vector<int> a;
        dfs(0, S.size(), S, a, 0);
        
        return ret;
    }
};



leetcode || 78、Subsets

标签:leetcode   dfs   集合   子集   回溯法   

原文地址:http://blog.csdn.net/hustyangju/article/details/44975105

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!