这个题目目的是为了求所有的子集,方法是遍历每个数字加进集合,比如最开始是[],加入1变成[1],再加上原来有的[],变成[] [1],遍历到2 ,加上2 变成[2] [1,2]加上原来的[] [1] 变成[][1] [2] [1,2],代码如下:
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums) == 0:
return res
res.append([])
for n in nums:
temp = []
for t in res:
m = t + [n]
temp.append(m)
res = res + temp
return res
回溯法:
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0:
return []
res = []
temp = []
self.hs(nums, res, temp, 0)
return res
def hs(self, nums, res, temp, i):
if i == len(nums):
res.append(temp)
return
self.hs(nums, res, temp+[nums[i]], i+1)
self.hs(nums, res, temp, i+1)