77. 组合
https://leetcode-cn.com/problems/combinations/
解法一:dfs回溯
从1~n中dfs遍历,每层递归取一位加入tmpList末尾,当tmp长度等于k时,复制到res中。
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
self.res = []
tmpList = []
self.dfs(n, k, tmpList, 1) #从1开始dfs
return self.res
def dfs(self, n, k, tmpList, start):
if len(tmpList) == k:
self.res.append(list(tmpList)) #注意要用复制,而不是直接加入
for i in range(start, n+1):
self.dfs(n, k, tmpList + [i], i+1) #start为i后一位
最后更新于