[LeetCode] 216. Total composition III

Topic links: https://leetcode-cn.com/problems/combination-sum-iii/

Subject description:

And the sum of all to find a combination of the number n of k. Composition may only contain 1-- 9 positive integer, and repeatable number does not exist in each combination.

Description:

  • All numbers are positive integers.
  • Solution Set can not contain duplicate combinations thereof.

Example:

Example 1:

输入: k = 3, n = 7
输出: [[1,2,4]]

Example 2:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]

Ideas:

A thought: library functions

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        return [item for item in itertools.combinations(range(1, 10), k) if sum(item) == n]

Thinking two: backtracking algorithm

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        res = []
        def helper(k, start, n, tmp):
            if k == 0:
                if n == 0:
                    res.append(tmp)
                return 
            for i in range(start, 10):
                if n - i < 0 :break
                helper(k - 1, i + 1, n - i, tmp + [i])
        helper(k, 1, n, [])
        return res

Guess you like

Origin www.cnblogs.com/powercai/p/11409639.html