diff --git a/problems/0078.子集.md b/problems/0078.子集.md index 878133a1..1ffc51ea 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -207,17 +207,28 @@ class Solution { ## Python ```python3 class Solution: + def __init__(self): + self.path: List[int] = [] + self.paths: List[List[int]] = [] + def subsets(self, nums: List[int]) -> List[List[int]]: - res = [] - path = [] - def backtrack(nums,startIndex): - res.append(path[:]) #收集子集,要放在终止添加的上面,否则会漏掉自己 - for i in range(startIndex,len(nums)): #当startIndex已经大于数组的长度了,就终止了,for循环本来也结束了,所以不需要终止条件 - path.append(nums[i]) - backtrack(nums,i+1) #递归 - path.pop() #回溯 - backtrack(nums,0) - return res + self.paths.clear() + self.path.clear() + self.backtracking(nums, 0) + return self.paths + + def backtracking(self, nums: List[int], start_index: int) -> None: + # 收集子集,要先于终止判断 + self.paths.append(self.path[:]) + # Base Case + if start_index == len(nums): + return + + # 单层递归逻辑 + for i in range(start_index, len(nums)): + self.path.append(nums[i]) + self.backtracking(nums, i+1) + self.path.pop() # 回溯 ``` ## Go