# LeetCode78:Subsets

Given a set of distinct integers, 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,3], a solution is:

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

# 解法一：位操作

000 对应[]
001 对应[3]
010 对应[2]
011 对应[2,3]
100 …
101
110
111

runtime:8ms

class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int length=nums.size();
sort(nums.begin(),nums.end());
vector<vector<int> > result;
for(int i=0;i<1<<length;i++)
{
vector<int> tmp;
//计算i中有那几位为1
for(int j=0;j<length;j++)
{
//判断i中第j位是否为1
if(i&1<<j)
{
tmp.push_back(nums[j]);
}
}
result.push_back(tmp);
}
return result;
}

};

# 解法二：回溯法

runtime:8ms

class Solution {
public:
//使用深度优先的回溯法
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> result;
vector<int> path;
sort(nums.begin(),nums.end());
result.push_back(path);
dfs(nums,0,path,result);
return result;
}
void dfs(vector<int>& nums,int pos,vector<int> & path,vector<vector<int>> & result)
{
if(pos==nums.size())
return;

for(int i=pos;i<nums.size();i++)
{
path.push_back(nums[i]);
result.push_back(path);
dfs(nums,i+1,path,result);
path.pop_back();
}
}

};

06-07 6413

02-08 2954

01-24 1428

08-05 1044

06-28 45

01-05 150

02-16 999

09-14 158

04-08 561

11-18 1143