# 【已解决】 78. Subsets【39、40未解决】

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;
}

};
• 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

# 解法二：回溯法

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]);
printf("%d\n",pos);
printV(path);

result.push_back(path);
dfs(nums,i+1,path,result);
path.pop_back();
printV(path);
}
}

};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120