与subsets类似,但是需要跳过重复的节点,加入while(level+1<nums.size()&&nums[level]==nums[level+1])level++;
[]
/ \
/ \
/ \
[1] []
/ \ / \
/ \ / \
[1 2] [1] [2] []
/ \ / \ / \ / \
[1 2 2] [1 2] X [1] [2 2] [2] X []
如图所示,只需跳过未添加重复节点的节点如[1],[]
void DFS(vector<vector<int>>& res, vector<int>& out, vector<int>& nums,int level) {
if (level == nums.size()) {
res.push_back(out);
return;
}
else
{
out.push_back(nums[level]);
DFS(res, out, nums, level+1);
out.pop_back();
while(level+1<nums.size()&&nums[level]==nums[level+1])level++;
DFS(res, out, nums, level+1);
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
vector<int> out;
DFS(res, out, nums,0);
return res;
}