python实现 LeetCode39——Combination Sum

利用递归的方式求得和为定值的数,如果目标值小于0,肯定不是解,就break。


class Solution(object):
    def combinationSum(self, candidates, target):
        candidates = list(set(candidates))
        sorted(candidates)
        self.result= []
        start=0
        self.backtrack(candidates, target,start,[])
        return self.result
    def backtrack(self,candidates,target,start,val):
        if target == 0:
            self.result.append(val[:])
        for i in range(start,len(candidates)):
            if target>0:
                val.append(candidates[i])
            else:
                break
            self.backtrack(candidates, target - candidates[i], i,val)
            val.pop()

你可能感兴趣的:(python学习,leetcode)