leetcode-78 子集
leetcode-78 子集
题目描述:
找出数组的所有子集
使用python自带的排列组合函数,注意,i的长度要包含序列长度;
from itertools import combinations
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
for i in range(len(nums)+1):
res.extend(combinations(nums,i))
res = [list(v) for v in res]
return res
自己实现的深搜
from itertools import combinations
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def dfs(nums,index,path):
res.append(path)
for i in range(index,len(nums)):
dfs(nums,i+1,path+[nums[i]])
res = []
nums.sort()
dfs(nums,0,[])
return res