python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
# 思路是回溯,这道题和【全排列】不一样的地方是出递归(收获)的判断条件不一样
def dfs(path,index,res):
res.append(path[:])
for i in range(index,len(nums)):
path.append(nums[i])
dfs(path,i+1,res)
path.pop()
res=[]
dfs([],0,res)
return res
思路是:
- 回溯和递归
- 我怎么感觉这种题背下来就好?
解法二
python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
# 思路是每一个元素都有取和不取两种选择:
def backtrack(path,index,res):
if index==len(nums):
res.append(path[:])
return
backtrack(path+[nums[index]],index+1,res)
backtrack(path,index+1,res)
res=[]
backtrack([],0,res)
return res
思路是:
- 每一个元素都有选和不选两个选择