Description
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
Example
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
思路
- 回溯,然后注意去重问题
代码
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
vector<int> vec;
subsetWithDupBacktrack(res, vec, nums, 0);
return res;
}
void subsetWithDupBacktrack(vector<vector<int>>& res, vector<int>& vec,
vector<int>& nums, int t){
res.push_back(vec);
for(int i = t; i < nums.size(); ++i){
if(i == t || nums[i] != nums[i - 1]){
vec.push_back(nums[i]);
subsetWithDupBacktrack(res, vec, nums, i + 1);
vec.pop_back();
}
}
}
};