90 [LeetCode] Subsets2

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]





class Solution {
public:
  vector<vector<int>> subsetsWithDup(vector<int> &S) {
        vector<vector<int>> totalset = {{}};
        sort(S.begin(),S.end());
        for(int i=0; i<S.size();){
            int count = 0; // num of elements are the same
            while(count + i<S.size() && S[count+i]==S[i])  count++;
            int previousN = totalset.size();
            for(int k=0; k<previousN; k++){
                vector<int> instance = totalset[k];
                for(int j=0; j<count; j++){
                  
                    instance.push_back(S[i]);
                      totalset.push_back(instance);
                    
                }
            }
            i += count;
        }
        return totalset;
        } 
};
原文地址:https://www.cnblogs.com/250101249-sxy/p/10426881.html