【算法刷题】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],
  []
]

 

即,S中的数字可以重复,因此得到的子数组有些可能会重复  要剔除重复的

class Solution {
public:
    void dfs(vector &S,vector &temp,int len,int pos)
    {

        res.push_back(temp);
        for(int i=pos;ipos && S[i]==S[i-1])
                continue;
            temp.push_back(S[i]);
            dfs(S,temp,len,i+1);
            temp.pop_back();
        }    
    }
    
    
    vector > subsetsWithDup(vector &S) {
        res.clear();
        vector inum;
        int len = S.size();
        if(len==0)
            return res;
        //排序,可以使重复的数字在一起
        sort(S.begin(),S.end());
        
        dfs(S,inum,len,0);
        return res;
        
    }
    
    vector > res;
};

 

你可能感兴趣的:(算法题)