解题思路-leetcode第四十题:组合总和Ⅱ
给定一个数组 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题组合总数十分相似,区别就是列表内的数字是否可以重复使用,所以本题的方法是基于39题的改进,即在递归函数内增加一个变量i,用于控制递归函数内遍历列表的位置,保证每一次遍历都是从上一层遍历元素的下一个元素开始,从而避免使用重复元素。代码如下:
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
def search(re,result,nums,t,i):
if sum(re)>t:
return
if sorted(re) not in result and sum(re) == t:
result.append(sorted(re))
return
for i in range(i, len(nums)):
search(re+[nums[i]],result,nums,t,i+1)
result = []
search([],result,candidates,target,0)
return result
提交后,通过。
本文详细解析了LeetCode第40题“组合总和Ⅱ”的解题思路,该题旨在寻找数组中所有可能的组合,使组合中的数字和为目标数,且每个数字在每个组合中只能使用一次。文章提供了Python实现的解决方案,并通过示例进行说明。
231

被折叠的 条评论
为什么被折叠?



