Description
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]
Submissions
这道题与上一题解题思路类似,它们都可以使用数组内任意个数的元素,但上一题可以重复,这一题不可以重复。上一题我们在递归函数中利用start参数来实现重复,而这道题我们利用i+1使遍历实现不重复。首先遍历candidates列表,当其小于target时添加到res中,最后当res列表中元素相加等于target时,判断res是否包含在结果result中,如果没有则添加到结果中,最后返回最终结果result。
实现代码如下:
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
candidates.sort()
def com(candidates, target, i, res):
if target == 0 and res not in result:
result.append(res)
for i in range(i, len(candidates)):
if candidates[i] > target:
return
com(candidates, target-candidates[i], i+1, res+[candidates[i]])
com(candidates, target, 0, [])
return result