90 Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example, If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Solution:
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
vector<int> tmp;
res.push_back(tmp);
sort(nums.begin(), nums.begin()+nums.size());
int i = 0;
while ( i <= nums.size()-1 ) {
int icount = 0, ni = nums[i];
while ( i <= nums.size()-1 and nums[i] == ni ) {
icount += 1;
i += 1;
}
int nres = res.size();
for ( int j = 0; j <= nres-1; j++ ) {
tmp = res[j];
for ( int k = 1; k <= icount; k++ ) {
tmp.push_back(ni);
res.push_back(tmp);
}
}
}
return res;
}
};
Note: sort an array in C++:
sort(nums.begin(), nums.begin()+nums.size());