class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
paths = []
path = []
def backtrack(n, k, start):
if len(path) == k:
paths.append(path[:])
for i in range(start, n+1):
path.append(i)
backtrack(n, k, i+1)
path.pop()
backtrack(n, k, 1)
return paths
优化一下
k-len(path)用来检测还需要多少元素,在1-n中至多要从该起始位 n - (k - len(path) + 1,开始遍历,+1代表左闭集合
距离n=k=4,则第一层为例,i最多取到1,对应结果[1,2,3,4]
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
paths = []
path = []
def backtrack(n, k, start):
if len(path) == k:
paths.append(path[:])
return
for i in range(start, n-(k-len(path)) + 2):
path.append(i)
backtrack(n, k, i+1)
path.pop()
backtrack(n, k, 1)
return paths