6.回溯算法-组合总和1.py

# 给你一个无重复元素的整数数组candidates和一个目标整数target ,找出candidates中可以使数字和为目标数target
# 的所有不同组合 ,并以列表形式返回。你可以按任意顺序返回这些组合。
#
# candidates中的同一个数字可以无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
# 对于给定的输入,保证和为target的不同组合数少于150个。
#
#
#
# 示例1:
# 输入:candidates = [2, 3, 6, 7], target = 7
# 输出:[[2, 2, 3], [7]]
# 解释:2和3可以形成一组候选,2 + 2 + 3 = 7 。
# 注意2可以使用多次。
# 7也是一个候选, 7 = 7 。仅有这两种组合。
#
#
# 示例2:
# 输入: candidates = [2, 3, 5], target = 8
# 输出: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
#
# 示例3:
# 输入: candidates = [2], target = 1
# 输出: []

candidates = [2, 3, 6, 7]
target = 7
path = []
res = []


def call_back(start_index, candidates, path):
    if sum(path)>target:
        return
    if sum(path) == target:
        res.append(path[:])
        return
    for i in range(start_index, len(candidates)):
        path.append(candidates[i])
        call_back(i, candidates, path)
        path.pop()
    return res

result = call_back(0, candidates, path)
print(result)


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值