iven 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],
[]
]
解题思路(1):这道题也就是要求求出所有的子集,可以用深度优先遍历来求解(有可能复杂度会爆,为指数级),每个数字都可能是俩种状态,一种是0,一种是1.从左子树走是0,从右子树走是1
解题思路(2):我们可以用位操作来做,n位就有2的n次方个子集,那么我只要包括这些个结果可以,如对于数组[1,2,3],可以用一个下标0和1表示是否选择该数字,0表示未选择,1表示选中,那么每一组3个0和1的组合表示一种选择,3位共有8种选择,分别是:
000 对应[]
001 对应[3]
010 对应[2]
011 对应[2,3]
100 …
101
110
111
那么上面为1的位表示数组中该位被选中。 0代码没有选中。我们可以参考python代码
C++代码
class Solution {
public:
void solve_subset(int level,vector<int>temp,vector<vector<int>>& res,vector<int>& nums) //res传入引用表达一直就是这个
{
if(level==nums.size())
{
res.push_back(temp);
return;
}
solve_subset(level+1,temp,res,nums); //这相当于左子树
temp.push_back(nums[level]);
solve_subset(level+1,temp,res,nums); //这相当于右子树
}
vector<vector<int>> subsets(vector<int>& nums) {
//这就是返回所有的子集,用搜索试试
//搜索是一定可以构造搜索树的
vector<vector<int>>res;
vector<int>temp;
solve_subset(0,temp,res,nums);
return res;
}
};
python代码:
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
len1 = len(nums)
maxx = 1<<len1
print maxx
for i in range(maxx):
temp = []
idx = 0
j = i
while j>0:
if j&1==1:
temp.append(nums[idx])
idx+=1 #反正全部是逆过来了,没关系,本来应该从最后开始向前减的
j = j>>1
print 'j=',j
res.append(temp) #第一个没进去,就是加进去空了
return res
知乎主页:忆臻
专栏地址:机器学习算法
博客地址:
忆臻博客