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

 

 

歡迎關注微信公衆號——計算機視覺:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章