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 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] ]
LeetCode:链接
40Combination Sum II这道题跟上题区别不大,只是限制了每个数字只能使用一次,所以for的时候i的起始位置就不是每次都从第一个数字添加了,而是要后移的。并且这个为了结果的去重,必须先将C数组排序,然后回溯的时候是从小到大的。
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
ans, res = [], []
candidates.sort()
self.backtracking(candidates, target, 0, ans, res)
return res
def backtracking(self, candidates, target, start, ans, res):
# 去重
if target == 0 and ans not in res:
res.append(ans)
else:
for i in range(start, len(candidates)):
# 小于candidates[i] 可以减少判断时间
if target < candidates[i]:
break
# i+1是为了限制每个数字只能使用一次
self.backtracking(candidates, target-candidates[i], i+1, ans+[candidates[i]], res)