77.组合
要点
- 理解回溯算法的模板和思想。
- 理解剪枝的运用。
代码
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res = []
path = []
def backtrack(n, k, start_index):
if len(path) == k:
res.append(path[:])
return
last_index = n - (k - len(path)) + 1
for i in range(start_index, last_index + 1):
path.append(i)
backtrack(n, k, i + 1)
path.pop()
backtrack(n ,k, 1)
return res