leetcode 40 组合总和 ||

本文探讨了一道经典算法问题:给定数组candidates和目标数target,找出candidates中所有可能使数字和等于target的组合。candidates中的每个数字在每个组合中只能使用一次。文章提供了Python实现的深度优先搜索+回溯解法,并详细解释了解题思路。

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

题目描述

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

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

说明:

所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。 
示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]

解题思路

这一题与39题的区别是candidates中的数字是否能够重复使用。

同样的,可以采用39题的深度优先搜索+回溯解法,然后限制每个数字使用一次,在最后的结果中加一步去除重复组合的步骤即可。

## 测试用例 [10,1,2,7,6,1,5] 8

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:


        size = len(candidates)
        if size == 0:
            return []
        
        def dfs(begin,res,path,target):
            if target == 0:
                ## 由于candidates中存在重复数字,
                ## 所以在最后的结果中需要做一步去重判断
                if path[:] not in res:
                    res.append(path[:])
                return 
            for index in range(begin,size):
                residul = target - candidates[index]
                if residul < 0:
                    break
                path.append(candidates[index])
                ## 从当前数字的下一位开始进行组合,
                ## 保证当前数字在组合中只被使用一次
                dfs(index+1,res,path,residul)
                path.pop()
        path = []
        res = []
        candidates.sort()
        dfs(0,res,path,target)
        return res 
            

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nobrody

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值