combination-sum-ii.py (697B)
1 class Solution: 2 def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 3 candidates.sort() 4 return find_all([], target, candidates, 0, set()) 5 6 7 def find_all(current, target, candidates, index, used): 8 9 if str(current) in used: 10 return [] 11 else: 12 used.add(str(current)) 13 14 if target == 0: 15 return [current] 16 17 ret_ls = [] 18 19 while index < len(candidates) and candidates[index] <= target: 20 21 copy_ls = current.copy() 22 copy_ls.append(candidates[index]) 23 24 ret = find_all(copy_ls, target - candidates[index], candidates, index + 1, used) 25 26 ret_ls.extend(ret) 27 28 index += 1 29 30 return ret_ls