1. 程式人生 > >python leetcode 39. Combination Sum

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()