代码随想录算法训练营|77. 组合
77. 组合
题目链接: 77. 组合
文档讲解: 代码随想录
题目难度:中等
思路:将问题具象化为高度固定的二叉树,树的宽度为集合长度n,高度为k的大小
时间复杂度:O(n*2^n);空间复杂度:O(n)
下面展示 代码
:
class Solution:
def backtracking(self, n,k,start,path,res):
if len(path) == k:
res.append(path[:]) # 终止条件
return
else:
for i in range(start, n-(k-len(path)) + 2):
path.append(i)
self.backtracking(n,k,i + 1,path,res)
path.pop() # 回溯
def combine(self, n: int, k: int) -> List[List[int]]:
if n == 1 and k == 1:
return [[1]]
else:
res = []
self.backtracking(n ,k, 1, [], res) # [1,N]
return res