mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0078.子集.md
This commit is contained in:
@ -206,28 +206,20 @@ class Solution {
|
|||||||
## Python
|
## Python
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def __init__(self):
|
def subsets(self, nums):
|
||||||
self.path: List[int] = []
|
result = []
|
||||||
self.paths: List[List[int]] = []
|
path = []
|
||||||
|
self.backtracking(nums, 0, path, result)
|
||||||
|
return result
|
||||||
|
|
||||||
def subsets(self, nums: List[int]) -> List[List[int]]:
|
def backtracking(self, nums, startIndex, path, result):
|
||||||
self.paths.clear()
|
result.append(path[:]) # 收集子集,要放在终止添加的上面,否则会漏掉自己
|
||||||
self.path.clear()
|
# if startIndex >= len(nums): # 终止条件可以不加
|
||||||
self.backtracking(nums, 0)
|
# return
|
||||||
return self.paths
|
for i in range(startIndex, len(nums)):
|
||||||
|
path.append(nums[i])
|
||||||
def backtracking(self, nums: List[int], start_index: int) -> None:
|
self.backtracking(nums, i + 1, path, result)
|
||||||
# 收集子集,要先于终止判断
|
path.pop()
|
||||||
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
|
## Go
|
||||||
|
Reference in New Issue
Block a user