2019-05-31LeetCode77. 组合

标准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

你可能感兴趣的:(2019-05-31LeetCode77. 组合)