Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inC where the candidate numbers sums to T.
Each number in C 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.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]思路:和上题的区别在于每个数只能用一次,所以每次都从i+1开始,另外会有重复情况,所以排序完后相邻相同数字不再重复使用。
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
res = []
self.dfs(candidates, target, 0, [], res)
return res
def dfs(self, nums, target, start, path, res):
if target == 0:
res.append(path)
return
if target < 0:
return
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i-1]:
continue
self.dfs(nums, target-nums[i], i+1, path+[nums[i]], res)