组合总和2

candidates 中的每个数字在每个组合中只能使用一次。

class Solution:
    def combinationSum2(self, candidates, target):
        # 将数组进行升序排序
        candidates.sort()

        # 结果列表
        ans = []
        # 可能组合
        tmp = []

        def helper(idx, total):
            if total == target:
                ans.append(tmp[::])
                return
            if total > target:
                return

            for i in range(idx, len(candidates)):
                # 这里限制同一层不能选择值相同的元素
                # 若有相同的元素,优先选择索引靠前的
                if candidates[i - 1] == candidates[i] and i - 1 >= idx:
                    continue

                total += candidates[i]
                tmp.append(candidates[i])
                # 这里注意,与 39 题不同,进入递归下一层
                # 从当前索引的下一位开始选取,避免重复选取同个元素
                helper(i + 1, total)
                # 回溯
                tmp.pop()
                total -= candidates[i]

        total = 0
        helper(0, total)
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值