LLancelot / LeetCode

✍️ My LeetCode solutions, ideas and templates sharing. (我的LeetCode题解,思路以及各专题的解题模板分享。分专题归纳,见tag)
https://leetcode.com/lancelot_/
163 stars 40 forks source link

77. Combination #8

Open LLancelot opened 4 years ago

LLancelot commented 4 years ago

组合问题

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
 [2,4],
 [3,4],
 [2,3],
 [1,2],
 [1,3],
 [1,4],
]
class Solution(object):
    def combine(self, n, k):
        # init first combination
        nums = list(range(1, k + 1)) + [n + 1]

        output, j = [], 0

        while j < k:
            # add current combination
            output.append(nums[:k])
            # increase first nums[j] by one
            # if nums[j] + 1 != nums[j + 1]
            j = 0
            while j < k and nums[j + 1] == nums[j] + 1:
                nums[j] = j + 1
                j += 1
            nums[j] += 1

        return output