美文网首页
2019-05-31LeetCode77. 组合

2019-05-31LeetCode77. 组合

作者: mztkenan | 来源:发表于2019-05-31 22:35 被阅读0次

标准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. 组合

      本文链接:https://www.haomeiwen.com/subject/nientctx.html