回溯
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
'''
为了不重复 需要按照一定的顺序迭代
例 n = 4 k = 2
第一个数 第二个数
1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []
循环 + 递归
'''
res_list = []
path = []
def dfs(begin):
# path 记录递归路径上的数字
# 当path长度达到k时 终止递归
if len(path) == k:
# 存储一个副本
res_list.append(path[:])
return
# 循环列举第一个数的所有选择
for i in range(begin, n + 1):
path.append(i)
# 第一个数确定后 向下递归
# 下一层的开始数字为 第一个数 + 1
dfs(i + 1)
# 每轮递归完成后 清理path
# 开启第二轮循环
path.pop()
dfs(1)
return res_list
回溯 + 剪枝
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res_list = []
path = []
def dfs(begin):
if len(path) == k:
res_list.append(path[:])
return
# 此处加上了剪枝逻辑 对每轮循环的上界进行优化
# 举例 n = 7 k = 4
# 当len(path) == 1 还需 3 个元素 上界为 5
# 当len(path) == 2 还需 2 个元素 上界为 6
# 上界 + 剩余元素数 - 1 = n
# 剩余元素数 k - len(path)
# 上界 n - (k - len(path)) + 1
for i in range(begin, n - (k - len(path)) + 1 + 1):
path.append(i)
dfs(i + 1)
path.pop()
dfs(1)
return res_list