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],
[]
]
求给定数组的全部子集,可能有重复元素
DFS解决,先排序,对于每一个元素,可以选择使用,但是若不使用,则需要将和它值相同的元素全部移除。
代码语言:javascript复制class Solution {
public:
void dfs(vector<vector<int>>& res,vector<int> nums,vector<int> now)
{
if(nums.size()==0)
{
res.push_back(now);
return ;
}
vector<int> temp=now;
int back=nums[nums.size()-1];
nums.pop_back();
now.push_back(back);
dfs(res,nums,now);
while(nums.size()>0 && nums[nums.size()-1]==back) nums.pop_back();//移除不使用的元素
dfs(res,nums,temp);
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
vector<int> now;
sort(nums.begin(),nums.end());
dfs(res,nums,now);
return res;
}
};