【LEETCODE】216-Combination Sum III [Python]

题目: https://leetcode.com/problems/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]]


题意:

找到所有 k 个数字的组合, 由这 k 个数字相加的和为 n

这几个数字只由 1 to 9 ,并且组合是唯一的,保证这个set的数字是升序的


参考:

http://bookshadow.com/weblog/2015/05/24/leetcode-combination-sum-iii/


回溯法:

http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html

回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。

但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,

这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。



Python

class Solution(object):
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        
        ans=[]
        
        def search(start,cnt,sums,nums):
            
            if cnt>k or sums>n:
                return
            if cnt==k and sums==n:
                ans.append(nums)
                return
            for x in range(start+1,10):
                search(x,cnt+1,sums+x,nums+[x])
        search(0,0,0,[])
        return ans


你可能感兴趣的:(LeetCode,python)