1、题目描述
给定一个候选人编号的集合 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates = [2,5,2,1,2], target = 5, 输出: [ [1,2,2], [5] ]
2、初始思路
2.1 思路
根据题目要求,每个数字在每个组合里只能用一次,也就是说,在每一支上,candidates中的数字都能取,但只能取一次;而且结果里不能有重复的组合,也就是说在每一层,当一个数取过之后,在candidates中与之数值相同的数字都不能再选取。因此,可以将本题的树状图抽象为:
2.2 代码
class Solution:def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:candidates.sort()res = []path = []def backtracking(candidates, target, startIndex):if target == 0:res.append(path.copy())returnfor i in range(startIndex, len(candidates)):#当取得数大于target时,说明该组合已经不成立,可直接跳出循环if candidates[i] > target:break#当一层中已经去过相同数值后,该数值不再被选取;但要注意在同一支中可从candidates中任选不重复的数值,因此需要用i > startIndex加以限制if i > startIndex and candidates[i] == candidates[i-1]:continuepath.append(candidates[i])backtracking(candidates, target - candidates[i], i+1 )path.pop()backtracking(candidates, target, 0)return res