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

Leetcode:Subsets 子集生成

时间:2014-06-29 00:03:40      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   get   

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

 

解题分析:

每个元素,都有两种选择,选或者不选。

为了保持子集有序,必须首先对原数组sort

class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        vector<vector<int>> result;
        if (S.size() == 0) return result;
        sort(S.begin(), S.end());   // sort
        vector<int> path;
        dfs(S, path, 0, result);
        return result;
    }
    
    void dfs(const vector<int>& S, vector<int>&path, int cur, vector<vector<int>>& result) {
        if (cur == S.size()) {
            result.push_back(path);
            return;
        }
        // not choose S[cur]
        dfs(S, path, cur + 1, result);
        // choose S[cur]
        path.push_back(S.at(cur));
        dfs(S, path, cur + 1, result);
        path.pop_back();
    }
};

 

 

Subsets II:

Given a collection of integers that might contain duplicatesS, 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,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

 

解题分析:

这题有重复元素,但本质上,跟上一题很类似,上一题中元素没有重复,相当于每个元素只能选0或1次,这里扩充到了每个元素可以选0到若干次而已

class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<vector<int>> result;
        if (S.size() == 0) return result;
        sort(S.begin(), S.end());
        vector<int> path;
        dfs(S, path, 0, result);
        return result;
    }
    
    void dfs(const vector<int>& S, vector<int>& path, int cur, vector<vector<int>>& result) {
        result.push_back(path);
        for (int i = cur; i < S.size(); ++i) {
            if (i != cur && S.at(i) == S.at(i-1)) {
                continue;
            }
            
            path.push_back(S.at(i));
            dfs(S, path, i + 1, result);
            path.pop_back();
        }
    }
};

 

 

Leetcode:Subsets 子集生成,布布扣,bubuko.com

Leetcode:Subsets 子集生成

标签:des   style   blog   http   color   get   

原文地址:http://www.cnblogs.com/wwwjieo0/p/3794160.html

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