# 78. Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

class Solution {
private:
vector<vector<int>> res;
public:
vector<vector<int>> subsets(vector<int>& nums) {
res.clear();
sort(nums.begin(),nums.end());
vector<int> tmp;
dfs(nums,0,tmp);
return res;
}
private:
void dfs(vector<int> nums,int index,vector<int>& tmp){
if(index == nums.size()){
res.push_back(tmp);
return;
}
tmp.push_back(nums[index]);
dfs(nums,index+1,tmp);
tmp.pop_back();
dfs(nums,index+1,tmp);
}
};

1处理完成之后，我们可以同样方式处理2，以及3。

class Solution {
public:
vector<vector<int> > res;
vector<vector<int> > subsets(vector<int> &S) {
res.clear();
vector<int> tmp;
//sort(S.begin(),S.end());
res.push_back(vector<int>());
dfs(S,0,tmp);
return res;
}
void dfs(vector<int> nums, int start, vector<int>& tmp){
if(start == nums.size()){
return ;
}
for(int i = start; i<nums.size(); i++){
tmp.push_back(nums[i]);
res.push_back(tmp);
dfs(nums,i+1,tmp);
tmp.pop_back();
}
}
};

subsets Ⅱ 是在subsetⅠ的基础上去重。思想类似。

class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
res.clear();
sort(nums.begin(),nums.end());
res.push_back(vector<int>());
vector<int> tmp;
dfs(nums,0,tmp);
return res;
}
void dfs(vector<int> nums, int start, vector<int> &tmp){
if(start == nums.size()){
return ;
}
vector<vector<int>>::iterator it = res.begin();
for(int i = start; i<nums.size(); i++){
tmp.push_back(nums[i]);
res.push_back(tmp);
dfs(nums,i+1,tmp);
tmp.pop_back();
while(i<nums.size()-1 && nums[i]==nums[i+1]){
i++;
}
}
}
};
• 本文已收录于以下专栏：

举报原因： 您举报文章：78. Subsets 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)