一、题设
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates =[10,1,2,7,6,1,5], target =8, 输出: [ [1,1,6], [1,2,5], [1,7], [2,6] ]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5, 输出: [ [1,2,2], [5] ]
二、基本思路
本题在39题做以下改动1.数组无序 2.不可以重复利用数据。在没有限制复杂度的情况下第一个问题很好解决,sort一下即可,第二个问题我起初是有两个思路:1.利用一个flag数组做标记 2.排序后在单层逻辑中跳过连续的重复数据,而每次选择后得使得i + 1跳过已经选择的数据。
三、代码实现
def combinationSum2(self, candidates, target):
def dfs(candidates,begin_index,path,res,target,size):
# 2.确定终止条件
if target < 0:
return
if target == 0:
res.append(path)
return
# 3.单层搜索逻辑
for i in range(begin_index,size):
if i > begin_index and candidates[i] == candidates[i-1]:
continue
# 改动2:每次选到了candidate[i]了,下次只能从i+1开始选了
dfs(candidates,i+1,path+[candidates[i]],res,target-candidates[i],size)
res = [] # 结果数组
path = [] # 中间数组存放路径
size = len(candidates)
# 改动1:排序
candidates.sort()
#return candidates
dfs(candidates,0,path,res,target,size)
return res
四、效率总结


本文详细介绍了组合总和II的问题,这是一个经典的回溯算法应用。题目要求在给定无序数组中找到所有不重复的组合,使它们的和为目标数。基本思路包括对数组进行排序,并在回溯过程中避免重复组合。提供的代码实现了一个深度优先搜索的解决方案,通过跳过重复元素来确保结果的唯一性。
——Topic40组合总和 II&spm=1001.2101.3001.5002&articleId=127372873&d=1&t=3&u=d0290a9ee607428e909db1ab8dd63f46)
662

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



