Leetcode 216. Combination Sum III

时间:2022-03-18 08:11:23

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

这一题和combiantion sum I/II 其实很类似。只不过candidates只有[1,2,...,9]。而且只有当len(line) == k 并且 sum(line) = n才把line添加到res里面。

 class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
nums = list(range(1,10))
res = []
self.helper(nums, k, n, res, [])
return res def helper(self, nums, k, target, res, line):
if target == 0 and len(line) == k:
res.append([x for x in line]) for i, x in enumerate(nums):
if x <= target:
line.append(x)
self.helper(nums[i+1:], k, target -x, res, line)
line.pop()