Combination Sum III

题目描述

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.

Ensure that numbers within the set are sorted in ascending order.

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]]

解题方法

combinations一样,不过要同时检查长度sum

Solution

class Solution(object):
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        results = []
        if k == 0 or n == 0:
            return []
        self.combHelper(k, n, results, 1, [])
        return results

    def combHelper(self, k, n, results, index, curList):
        if len(curList) == k and sum(curList) == n:
            tmpList = list(curList)
            results.append(tmpList)
        if len(curList) > k:
            return
        if sum(curList) > n:
            return

        for i in range(index, 10):
            curList.append(i)
            self.combHelper(k, n, results, i+1, curList)
            curList.pop()

Reference