Combination Sum

超过时间的递归做法

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        temp = []
        candidates.sort()
        self.dfs(candidates,res,temp,target,0)
        return res
    
    def dfs(self,candidates,res,temp,target,j):
        if target == 0:
            temp.sort()
            if temp not in res:
                res.append(temp)
        i = j
        while i < len(candidates) :
            if candidates[i] < target:
                temp.append(candidates[i])
                self.dfs(candidates,res,temp,target - candidates[i], j)
                temp.pop()
                i += 1

上面那种不太对
重新花了树,如图:


Combination Sum_第1张图片
WechatIMG74.jpeg

代码实现如下:

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        res = []
        self.dfs(candidates, target, res, [], 0)
        return res
    def dfs(self,candidates, target, res, temp, start):
        if target == 0:
            res.append(temp)
            return 
        if  start>= len(candidates):
            return
        if target < candidates[start]:
            return
        for i in range(start, len(candidates)):
            self.dfs(candidates, target - candidates[i], res, temp + [candidates[i]], i)
            ```

你可能感兴趣的:(Combination Sum)