LeetCode---39. Combination Sum

題目

給出一個數組,沒有重複元素,另給出一個目標值,找出所有的組合,組合的和爲目標值。注意:相同的元素可以重複無限次。

Python題解

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        res, path = [], []
        self.dfs(candidates, target, 0, path, res)
        return res

    def dfs(self, candidates, target, index, path, res):
        if target < 0:
            return
        if target == 0:
            res.append(path[:])
        for i in range(index, len(candidates)):
            self.dfs(candidates, target - candidates[i], i, path + [candidates[i]], res)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章