# 回溯编程模板
def backtracking(形参): # 返回值通常为空
if (终止条件):
存放结果
return
for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)):
处理节点
backtracking(路径,选择列表) # 递归
回溯,撤销处理结果
题目链接/文章讲解:https://programmercarl.com/0077.%E7%BB%84%E5%90%88.html
视频讲解:https://www.bilibili.com/video/BV1ti4y1L7cv
剪枝操作:https://www.bilibili.com/video/BV1wi4y157er
class Solution:
def backtracking(self, cur, n, k, single_set, result):
if len(single_set) == k:
result.append(single_set[:])
return
for i in range(cur, n - (k - len(single_set)) + 2):
single_set.append(i)
self.backtracking(i + 1, n, k, single_set, result)
single_set.pop()
def combine(self, n: int, k: int) -> List[List[int]]:
result = []
self.backtracking(1, n, k, [], result)
return result