边工作边刷题:70天一遍leetcode: day 19-2

Combination Sum III

这题似乎没什么玄机,和I/II思路类似,而且更简单:输入集合没有重复元素(所以不用考虑duplicate),一个数也不能用多次(所以下层recursion start+1)。
错误点:因为失败返回的条件比较多(len(res)>k or sum<0),start>9也有可能成功,所以成功条件要在失败之前。否则,有效结果中包含9的解会被漏掉。

class Solution(object):
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        def combine(start, sum, k, res, solutions):
            if sum==0 and len(res)==k:
                resCp = list(res)
                solutions.append(resCp)
                return
            
            if start>9 or len(res)>k or sum<0:
                return
            
            for i in range(start,10):
                res.append(i)
                combine(i+1, sum-i, k, res, solutions)
                res.pop()
                
        res = []
        solutions = []
        combine(1, n, k, res, solutions)
        return solutions
            
原文地址:https://www.cnblogs.com/absolute/p/5677919.html