Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- 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], [] ]
思路:回溯法比较难的一个点,就是怎么防止重复的情况出现,这里用一个record数组记录每个值出现与否,如果前后元素相同,而且前面的元素未被使用,那么说明会出现相同的情况,跳出。
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
vector<int> path;
vector<bool> record(nums.size(),false);
res.push_back(path);
sort(nums.begin(), nums.end());
dfs(0, path,record, nums, res);
return res;
}
void dfs(int level, vector<int> &path, vector<bool> &record,vector<int> &nums, vector<vector<int>> &res){
if (level == nums.size())
return;
for (int i = level; i < nums.size(); i++){
if (i>0 && nums[i] == nums[i - 1]&&!record[i-1])
continue;
else{
record[i] = true;
path.push_back(nums[i]);
res.push_back(path);
dfs(i + 1, path, record,nums, res);
path.pop_back();
record[i] = false;
}
}
}
};