描述
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Python
backtracking得到所有长度的组合
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
for k in range(len(nums)+1):
self.dfs(nums,k,0,[],res)
return res
def dfs(self,nums,k,index,path,res):
if k==0:
res.append(path)
return
for i in range(index,len(nums)):
self.dfs(nums,k-1,i+1,path+[nums[i]],res)
循环迭代
class Solution:
def subsets(self, nums):
res = [[]]
for num in nums:
res += [item+[num] for item in res]
return res