mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 04:54:51 +08:00
Update 0077.组合.md
This commit is contained in:
@ -377,68 +377,42 @@ class Solution {
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
未剪枝优化
|
||||
```python
|
||||
class Solution(object):
|
||||
def combine(self, n, k):
|
||||
"""
|
||||
:type n: int
|
||||
: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)
|
||||
class Solution:
|
||||
def combine(self, n: int, k: int) -> List[List[int]]:
|
||||
result = [] # 存放结果集
|
||||
self.backtracking(n, k, 1, [], 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
|
||||
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 + 1):
|
||||
path.append(i)
|
||||
backtrack(n, k, i+1)
|
||||
path.pop()
|
||||
backtrack(n, k, 1)
|
||||
return res
|
||||
```
|
||||
result = [] # 存放结果集
|
||||
self.backtracking(n, k, 1, [], 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 - (k - len(path)) + 2): # 优化的地方
|
||||
path.append(i) # 处理节点
|
||||
self.backtracking(n, k, i + 1, path, result)
|
||||
path.pop() # 回溯,撤销处理的节点
|
||||
|
||||
剪枝:
|
||||
|
||||
```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
|
||||
|
Reference in New Issue
Block a user