题目链接: https://leetcode.com/problems/subsets-ii/
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], [] ]
思路: 还是一个DFS, leetcode有很多类似的重复变形的题目, 和不包含重复元素的区别是在遍历到某个值时, 可以分为拿和不拿. 如果拿的话就按照正常往下一层搜索, 如果不拿当前值的话, 那么也要跳过接下来和当前值相等的元素.
代码如下:
class Solution {
public:
void DFS(vector<int>& nums, vector<int> vec, int k)
{
if(k >= nums.size()) return result.push_back(vec);
int x = k;
while(k+1 < nums.size() && nums[k] == nums[k+1]) k++;
DFS(nums, vec, k+1);
vec.push_back(nums[x]);
DFS(nums, vec, x+1);
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
if(nums.size()==0) return {};
sort(nums.begin(), nums.end());
DFS(nums, vector<int>(), 0);
return result;
}
private:
vector<vector<int>> result;
};