leetcode77组合

    def _combine(self, n, k, start, nums, result):
        if len(nums) == k:
            result.append(nums.copy())
            return

        # k - len(nums)
        for i in range(start, n - (k - len(nums)) + 2):
            nums.append(i)
            self._combine(n, k, i + 1, nums, result)
            nums.pop()

    def combine(self, n, k):
        """
        1.特殊值判断
        2.终止条件
        3.循环遍历 只能取后面的元素
        """
        result = list()
        if n <= 0 or k <= 0 or n < k:
            return result

        nums = list()
        self._combine(n, k, 1, nums, result)
        return result

 

你可能感兴趣的:(算法-leetcode,回溯)