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)

猜你喜欢

转载自blog.csdn.net/leel0330/article/details/80484189