LeetCode-90-子集II

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

1
2
3
4
5
6
7
8
9
10
输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//注意理解去重的思路
//time O(2^n)
//space O(kn)
class Solution {
private:
vector<vector<int>> res;
public:
//与无相同元素的区别:
//添加了排序,并在同层使用第一个
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<int> temp;
res.push_back(temp);//先将空集放入数组

if(nums.empty())
return res;

//根据子集的长度递增的方式依次回溯求出
for(int i=1;i<=nums.size();i++)
DFS(i,0,nums,temp);

return res;
}

//参数
//集合长度
void DFS(int length ,int start ,vector<int>& nums ,vector<int>& temp){
if(length==0){
res.push_back(temp);
return;
}

for(int i=start;i<nums.size();i++){
//同一层出现相同元素,只使用第一个,这样可以避免出现重复项,前提需要先对candidates排好序
if(i>start&&nums[i]==nums[i-1])
continue;
temp.push_back(nums[i]);
DFS(length-1,i+1,nums,temp);
temp.pop_back();
}
}
};

----\(˙<>˙)/----赞赏一下吧~