[leetcode] Subsets II

Subsets II

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

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

思路:

Subsets一样,只是这里原容器中有重复的元素,于是就增加一个去重。去重的方法我用的还是与leetcode上的另一个题目一样,开辟一个数组记录当前元素是否使用过。如果当前元素等于前一个元素,且前一个元素没有使用,那么当前元素就不能使用。

class Solution {
public:
    vector<vector<int> > res;
    void dfs(vector<int> &s, bool used[], int index, vector<int> tmp) {
        if(index==s.size()) {
            res.push_back(tmp);
            return;
        }
        dfs(s, used, index+1, tmp);
        if(!used[index]) {
            if(index!=0 && s[index]==s[index-1] && !used[index-1])
                return;
            used[index] = true;
            tmp.push_back(s[index]);
            dfs(s, used, index+1, tmp);
            used[index] = false;
        }
    }
    vector<vector<int> > subsetsWithDup(vector<int> &s) {
        sort(s.begin(), s.end());
        vector<int> tmp;
        int n = s.size();
        bool *used = new bool [n];
        memset(used, false, n);
        dfs(s, used, 0, tmp);
        return res;
    }
};
View Code

 

 

 

posted on 2015-01-06 19:32  cha1992  阅读(166)  评论(0编辑  收藏  举报

导航