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.
题意:给定一个集合(集合元素可能有重复),输出所有子集。
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res = {{}};//只有一个空集
int len = nums.size();
sort(nums.begin(), nums.end());//排序
for (int i = 0; i < len;) {
int count = 0;//元素nums[i]重复个数
while (count + i < len && nums[count+i] == nums[i]) count++;
int pN = res.size();
//分别向现有子集上,加入1~count个nums[i].
for (int j = 0; j < pN; ++j) {
vector<int> tmp = res[j];
for (int k = 0; k < count; ++k) {
tmp.push_back(nums[i]);
res.push_back(tmp);
}
}
i += count;
}
return res;
}
};