mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -207,17 +207,28 @@ class Solution {
|
|||||||
## Python
|
## Python
|
||||||
```python3
|
```python3
|
||||||
class Solution:
|
class Solution:
|
||||||
|
def __init__(self):
|
||||||
|
self.path: List[int] = []
|
||||||
|
self.paths: List[List[int]] = []
|
||||||
|
|
||||||
def subsets(self, nums: List[int]) -> List[List[int]]:
|
def subsets(self, nums: List[int]) -> List[List[int]]:
|
||||||
res = []
|
self.paths.clear()
|
||||||
path = []
|
self.path.clear()
|
||||||
def backtrack(nums,startIndex):
|
self.backtracking(nums, 0)
|
||||||
res.append(path[:]) #收集子集,要放在终止添加的上面,否则会漏掉自己
|
return self.paths
|
||||||
for i in range(startIndex,len(nums)): #当startIndex已经大于数组的长度了,就终止了,for循环本来也结束了,所以不需要终止条件
|
|
||||||
path.append(nums[i])
|
def backtracking(self, nums: List[int], start_index: int) -> None:
|
||||||
backtrack(nums,i+1) #递归
|
# 收集子集,要先于终止判断
|
||||||
path.pop() #回溯
|
self.paths.append(self.path[:])
|
||||||
backtrack(nums,0)
|
# Base Case
|
||||||
return res
|
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