Update 0077.组合.md

This commit is contained in:
jianghongcheng
2023-05-26 02:24:01 -05:00
committed by GitHub
parent 343e0775eb
commit 89e9d75cbf

View File

@ -377,68 +377,42 @@ class Solution {
``` ```
### Python ### Python
未剪枝优化
```python ```python
class Solution(object): class Solution:
def combine(self, n, k): def combine(self, n: int, k: int) -> List[List[int]]:
""" result = [] # 存放结果集
:type n: int self.backtracking(n, k, 1, [], result)
:type k: int
:rtype: List[List[int]]
"""
result = []
path = []
def backtracking(n, k, startidx):
if len(path) == k:
result.append(path[:])
return
# 剪枝, 最后k - len(path)个节点直接构造结果,无需递归
last_startidx = n - (k - len(path)) + 1
for x in range(startidx, last_startidx + 1):
path.append(x)
backtracking(n, k, x + 1) # 递归
path.pop() # 回溯
backtracking(n, k, 1)
return result return result
def backtracking(self, n, k, startIndex, path, result):
if len(path) == k:
result.append(path[:])
return
for i in range(startIndex, n + 1): # 需要优化的地方
path.append(i) # 处理节点
self.backtracking(n, k, i + 1, path, result)
path.pop() # 回溯,撤销处理的节点
``` ```
剪枝优化:
```python ```python
class Solution: class Solution:
def combine(self, n: int, k: int) -> List[List[int]]: def combine(self, n: int, k: int) -> List[List[int]]:
res = [] result = [] # 存放结果集
path = [] self.backtracking(n, k, 1, [], result)
def backtrack(n, k, StartIndex): return result
if len(path) == k: def backtracking(self, n, k, startIndex, path, result):
res.append(path[:]) if len(path) == k:
return result.append(path[:])
for i in range(StartIndex, n + 1): return
path.append(i) for i in range(startIndex, n - (k - len(path)) + 2): # 优化的地方
backtrack(n, k, i+1) path.append(i) # 处理节点
path.pop() self.backtracking(n, k, i + 1, path, result)
backtrack(n, k, 1) path.pop() # 回溯,撤销处理的节点
return res
```
剪枝:
```python
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res=[] #存放符合条件结果的集合
path=[] #用来存放符合条件结果
def backtrack(n,k,startIndex):
if len(path) == k:
res.append(path[:])
return
for i in range(startIndex,n-(k-len(path))+2): #优化的地方
path.append(i) #处理节点
backtrack(n,k,i+1) #递归
path.pop() #回溯,撤销处理的节点
backtrack(n,k,1)
return res
``` ```
### Go ### Go