LeetCode-40 Combination Sum II

本文探讨了一道算法题,题目要求在给定候选数字集合和目标数字的情况下,找出所有可能的唯一组合,使得组合内的数字之和等于目标值。每个数字在组合中只能使用一次,且解决方案不能包含重复的组合。文章提供了详细的解题思路和Python代码实现。

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

Description

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

Example

Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]

Submissions

这道题与上一题解题思路类似,它们都可以使用数组内任意个数的元素,但上一题可以重复,这一题不可以重复。上一题我们在递归函数中利用start参数来实现重复,而这道题我们利用i+1使遍历实现不重复。首先遍历candidates列表,当其小于target时添加到res中,最后当res列表中元素相加等于target时,判断res是否包含在结果result中,如果没有则添加到结果中,最后返回最终结果result。

实现代码如下:

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        candidates.sort() 
        def com(candidates, target, i, res):
            if target == 0 and res not in result:
                result.append(res)
            for i in range(i, len(candidates)):
                if candidates[i] > target:
                    return
                com(candidates, target-candidates[i], i+1, res+[candidates[i]])
                
        com(candidates, target, 0, [])
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值