Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
如果集合S里没有重复的数字,那么每个数字可能出现在subset,也可能不出现;如果集合S里有重复的数字,假设这个重复数字的个数是4,那么这个重复数字在subset里出现的次数可能是0、1、2、3、4. 根据这个观察,就可以写出如下的代码。
vector<vector<int> > subsetsWithDup(vector<int> &S) { sort(S.begin(), S.end()); // sort the input vector into increasing order vector<int> nums; // the unique set of numbers in S vector<int> counts; // the count of each number in nums // If input S=[1,2,2,3,3,3,3], then nums=[1,2,3], counts=[1,2,4] for(int i=0; i<S.size(); i++) { if(i==0) { nums.push_back(S[0]); counts.push_back(1); } else { if(S[i]==S[i-1]) counts[counts.size()-1]++; else { nums.push_back(S[i]); counts.push_back(1); } } } vector<int> result; vector<vector<int> > results; subsetsWithDupUtil(nums, counts, result, 0, results); return results; } void subsetsWithDupUtil(vector<int> & nums, vector<int>& counts, vector<int> result, int pos, vector<vector<int> >& results) { if(pos==nums.size()) { results.push_back(result); return; } for(int i=0; i<=counts[pos]; i++) { subsetsWithDupUtil(nums, counts, result, pos+1, results); result.push_back(nums[pos]); } }