难度:中等
给定一个数组 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题思路差不多,采取递归的方法解决,只不过每次的数组需要将本次递归的数据给剔除掉。
代码如下:
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
#结果集合
result = []
candidates.sort()
#递归函数
def a(temp,res,x):
#失败
if temp > target:
return
#找到符合的序列
if temp == target:
if res not in result:
result.append(res[:])
return
for i in range(0,len(x)):
#防止重复的方法是,不让其找在当前元素以前的元素
a(temp + x[i], res+[x[i]],x[i+1:])
#函数调用
a(0,[], candidates)
return result