77. 组合



还是套模板,模板可参考:https://www.cnblogs.com/panweiwei/p/14025143.html

class Solution(object):
    def __init__(self):
        self.res = []

    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        nums = [i for i in range(1, n+1)]
        sizeN = len(nums)
        self.dfs(nums, sizeN, k, 0, [])
        return self.res

    def dfs(self, nums, sizeN, k, begin, temp):
        # 定义递归出口:长度为k
        if len(temp) == k:
            self.res.append(temp)
        for i in range(begin, sizeN):
            if len(temp) > k:
                break
            # 递归
            self.dfs(nums, sizeN, k, i+1, temp+[nums[i]])
posted @ 2020-11-23 16:38  人间烟火地三鲜  阅读(118)  评论(0编辑  收藏  举报