组合总和(回溯算法)

本文深入探讨了组合求和算法,给出了两种不同的实现方式。一种是在candidates数组中每个数字只能使用一次的情况下找到所有可能的组合,使组合的数字之和等于目标数target。另一种是允许candidates中的数字可以无限次重复使用,同样寻找所有可能的组合。文章通过具体的代码示例展示了这两种算法的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。 
def combinationSum( candidates, target: int) :
        res=[];
        c_l=len(candidates);
        def find(output,newTarget,i,c_l):
        sorted(output):同一个数组,不同顺序是一样的
            if newTarget==0 and sorted(output) not in res:
                res.append(sorted(output));
                return;
            用来跳过这一k;防止重复计算当前值
            if i>=c_l:return;
            防止重复计算上一步的值;从上一步的i的i+1开始循环
            for k in range(i,c_l):
                now=candidates[k]
                new_target=newTarget-now;
                if new_target>=0:
                用来跳过这一k;防止重复计算当前值
                    find(output+[now],new_target,k+1,c_l)
        find([],target,0,c_l);
        return res
candidates=[2,3,6,7,5,6,1];
print(combinationSum(candidates,7))

[[2, 5], [1, 6], [7]]
candidates 中的数字可以无限制重复被选取。
def combinationSum2( candidates, target: int) :
        res=[];
        c_l=len(candidates);
        def find(output,newTarget,i,c_l):
            if newTarget==0 and sorted(output) not in res:
                res.append(sorted(output));
                return;
            为了可以重复使用上一步的值:就注释了下面的
            # if i>=c_l:return;
            for k in range(i,c_l):
                now=candidates[k]
                new_target=newTarget-now;
                if new_target >=0:
                k为当前index,为了可以重复使用当前值
                    find(output+[now],new_target,k,c_l)
        find([],target,0,c_l);
        return res
candidates=[2,3,6,7,5,1];
print(combinationSum2(candidates,7))


[
[1, 2, 2, 2], [2, 2, 3], [1, 1, 1, 2, 2],
 [1, 1, 2, 3], [2, 5],
  [1, 1, 1, 1, 1, 2], [1, 3, 3],
   [1, 1, 1, 1, 3], [1, 6], [7], [1, 1, 5],
    [1, 1, 1, 1, 1, 1, 1]
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值