40.
给定一个数组 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]
]
本题典型的回溯法
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
size = len(candidates)
candidates.sort()
res = []
pp = []
self.digui(candidates,0,size,target,res,pp)
return res
def digui(self,candidates,begin,size,target,res,pp):
if target==0 :
res.append(pp[:])
for index in range(begin,size):
residue = target - candidates[index]
if residue < 0:
break
pp.append(candidates[index])
#print(pp)
# 因为下一层不能比上一层还小,起始索引还从 index 开始
self.digui(candidates, index+1, size, residue,res,pp)
pp.pop()
#print(","+str(pp))