Open LLancelot opened 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], ]
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
组合问题