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>& nums) {
vector<vector<int>> ans={{}};
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();){
int cnt=0;
while(i+cnt<nums.size()&&nums[i]==nums[i+cnt]){
cnt++;
}
int N=ans.size();
for(int k=0;k<N;k++){
vector<int> tmp=ans[k];
for(int j=0;j<cnt;j++){
tmp.push_back(nums[i]);
ans.push_back(tmp);
}
}
i+=cnt;
}
return ans;
}
};
可以用回溯法,看成一个空间树,左子树表示加入当前节点,右子树不加入,然后为了去掉重复节点,当前层最后加入while语句过滤重复节点
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int> &S) {
if (S.empty()) return {};
vector<vector<int>> res;
vector<int> out;
sort(S.begin(), S.end());
getSubsets(S, 0, out, res);
return res;
}
void getSubsets(vector<int> &S, int pos, vector<int> &out, vector<vector<int>> &res) {
res.push_back(out);
for (int i = pos; i < S.size(); ++i) {
out.push_back(S[i]);
getSubsets(S, i + 1, out, res);
while (i + 1 < S.size() && S[i] == S[i + 1]) ++i;
out.pop_back();
}
}
};