给定一个数组 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的深度搜索的方法进行了一些加工,的确也是一个AC解
class Solution:
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
self.result = []
self.DFS(candidates, target, 0, [])
return self.result
def DFS(self, candidates, target, start, marklist):
if target == 0 and marklist not in self.result:
return self.result.append(marklist)
for i in range(start, len(candidates)):
if candidates[i] > target:
return
self.DFS(candidates, target - candidates[i], i+1, marklist+[candidates[i]])
方法二:
首先对于列表进行排序,然后依次进行查找,最后对于满足条件的需要去一下重复的元素
class Solution:
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
def findnum(candidates, target):
result = []
i = 0
while i < len(candidates):
if candidates[i] == target:
result.append([candidates[i]])
elif candidates[i] < target:
found = findnum(candidates[i+1:], target-candidates[i])
if found:
for temp in found:
temp.append(candidates[i])
result.append(temp)
else:
return result
i += 1
return result
result = findnum(candidates, target)
result1 = []
for item in result:
if item not in result1:
result1.append(item)
return result1