`

Subsets II(C++实现)

 
阅读更多

 

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

 

class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<vector<int> > ret;
        if(S.size() == 0) return ret;
        sort(S.begin(), S.end());
        vector<int> tmp;
        dfs(S, 0, tmp, ret);
        return ret;
    }
    
    void dfs(vector<int> &S, int beg, vector<int> tmp, vector<vector<int> > &ret) {
        ret.push_back(tmp);
        if(beg >= S.size()) return;
        for(int i = beg; i < S.size(); ++i) {
            if(i == beg || S[i] != S[i-1]) {
                tmp.push_back(S[i]);
                dfs(S, i+1, tmp, ret);
                tmp.pop_back();
            }
        }
    }
};

 

 

欢迎关注微信公众号——计算机视觉:

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics