标准dfs,5min
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res=[]
self.dfs(1,res,[],n,k)
return res
def dfs(self,start,res,path,n,k):
if len(path)==k:
res.append(path+[])
return
for i in range(start,n+1):
path.append(i)
self.dfs(i+1,res,path,n,k)
path.pop()
使用内函数
class Solution3:
def combine(self, n: int, k: int) -> List[List[int]]:
def back(start=1,path=[]):
if len(path)==k:
res.append(path+[])
return
for i in range(start,n+1):
path.append(i)
back(i+1,path)
path.pop()
res=[]
back()
return res
网友评论