python leetcode 39. Combination Sum

DFS,注意能不能重复取,这里能重复取,所以每次都是从头遍历。

class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        self.reslist=[]
        candidates.sort()
        self.dfs(candidates, [], target, 0)
        return self.reslist
    def dfs(self, candidates, sublist, target, last):
        if target ==0:
            return self.reslist.append(sublist[:])
        if target < candidates[0]:
            return 
        for n in candidates:
            if target < n:
                return 
            if n < last:
                continue 
            sublist.append(n)
            self.dfs(candidates,sublist,target-n,n)
            sublist.pop()

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84872652