Problem Statement
(Source) Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C 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 target 8,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Solution
class Solution(object):
def bt(self, candidates, target, res, ass, start_index):
if target == 0:
res.add(tuple(ass))
else:
for index in xrange(start_index, len(candidates)):
if candidates[index] > target:
break
ass.append(candidates[index])
self.bt(candidates, target - candidates[index], res, ass, index + 1)
ass.pop()
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
res = set()
self.bt(candidates, target, res, [], 0)
return [list(x) for x in res]