题:给定一个数组,返回所有可能的子集。来源:Leetcode(力扣)
1、遍历,遇到一个数就把所有子集加上该数组成新的子集,遍历完毕即是所有子集。
2、将问题的解空间转化成树的结构,通过深度优先遍历(回溯)得到树的所有叶子节点即为所求结果。
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
re = []
path = []
self.dfs(re, nums,path,0)
return re
def dfs(self,re,nums,path,index):
if index >= len(nums):
re.append(path.copy())
return
path.append(nums[index])
self.dfs(re, nums, path, index + 1)
path.pop()
self.dfs(re, nums, path, index + 1)
??