From d45c141cc676cf0ef55dccd85705f3eb5c8323a7 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 27 May 2023 18:38:57 -0500 Subject: [PATCH] =?UTF-8?q?Update=200078.=E5=AD=90=E9=9B=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0078.子集.md | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/problems/0078.子集.md b/problems/0078.子集.md index f26d0821..ecc202b7 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -206,28 +206,20 @@ class Solution { ## Python ```python class Solution: - def __init__(self): - self.path: List[int] = [] - self.paths: List[List[int]] = [] + def subsets(self, nums): + result = [] + path = [] + self.backtracking(nums, 0, path, result) + return result - def subsets(self, nums: List[int]) -> List[List[int]]: - 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() # 回溯 + def backtracking(self, nums, startIndex, path, result): + result.append(path[:]) # 收集子集,要放在终止添加的上面,否则会漏掉自己 + # if startIndex >= len(nums): # 终止条件可以不加 + # return + for i in range(startIndex, len(nums)): + path.append(nums[i]) + self.backtracking(nums, i + 1, path, result) + path.pop() ``` ## Go