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

思考:直接set去重会不会太暴力。。

class Solution {
private:
    vector<vector<int> > res;
    vector<int> ans;
    set<vector<int> > m;
public:
    void DFS(vector<int> S,int n,int start,int dep,int k)
    {
        if(dep==k)
        {
            set<vector<int> >::iterator iter=m.find(ans);
            if(iter==m.end())
            {
                res.push_back(ans);
                m.insert(ans);
            }
            return;
        }
        for(int i=start;i<n-k+1;i++)
        {
            ans.push_back(S[i+dep]);
            DFS(S,n,i,dep+1,k);
            ans.pop_back();
        }
    }
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        res.clear();
        ans.clear();
        int n=S.size();
        sort(S.begin(),S.end());
        for(int k=0;k<=n;k++)
        {
            DFS(S,n,0,0,k);
        }
        return res;
    }
};

  

原文地址:https://www.cnblogs.com/Rosanna/p/3521290.html