组合总和(python实现)

题目描述:

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的数字可以无限制重复被选取。
链接:https://leetcode-cn.com/problems/combination-sum

示例:

解题思路:回溯

a)用目标值target减去数组candidates中的元素值,得到新的目标值target,不断与数组candidates中的元素值执行减法操作,至目标值为0或负数;
b)目标值为0的路径值组合则为所求;
举例:candidates = [2,3,6,7]   target = 7
                                                            7
                     -2                         -3                      -6                          -7
                     5                          4                       1                           0
        -2         -3       -6      -7
        3          2       -1      -2
-2   -3   -6   -7
1    0   -3   -4

代码实现:

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        组合总和
        解题思路:回溯
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        path = []
        length = len(candidates)
        start = 0  # 加入start起始位置,是为结果中不含重复项;即当-2这一分枝结束后,下一分枝将不会出现-2操作;
        self.dfs(candidates, target, start, length, res, path)
        return res

    def dfs(self, candidates, target, start, length, res, path):
        if target < 0:  # 目标数小于0时,直接结束不做操作
            return
        if target == 0:  # 目标数为0时,将path加入结果集中
            res.append(path)
            return
        for idx in range(start, length):
            self.dfs(candidates, target - candidates[idx], idx, length, res, path + [candidates[idx]])

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值