LeetCode-78-子集

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

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

示例:

1
2
3
4
5
6
7
8
9
10
11
12
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[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
//time O(2^n)
//space O(kn)
class Solution {
private:
vector<vector<int>> res;
public:
vector<vector<int>> subsets(vector<int>& nums) {
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++){
temp.push_back(nums[i]);
DFS(length-1,i+1,nums,temp);
temp.pop_back();
}
}
};

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