|
| 1 | +class Solution: |
| 2 | + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: |
| 3 | + # sort since if we add an index and it's greater, |
| 4 | + # then adding any index past that will also be greater |
| 5 | + candidates.sort() |
| 6 | + |
| 7 | + def helper(currTotal: int = 0, |
| 8 | + currIndx: int = 0, |
| 9 | + valsSoFar: List[int] = [], |
| 10 | + output: List[int] = []) -> List[int] : |
| 11 | + if currTotal == target : |
| 12 | + output.append(valsSoFar.copy()) |
| 13 | + return output |
| 14 | + |
| 15 | + if currTotal > target : |
| 16 | + return output |
| 17 | + |
| 18 | + # Iterate through each next potential value till too big |
| 19 | + while currIndx < len(candidates) and candidates[currIndx] + currTotal <= target : |
| 20 | + # To avoid repeat combinations, jump past the group of same values |
| 21 | + startIndx, endIndx = currIndx, currIndx |
| 22 | + while endIndx < len(candidates) and candidates[endIndx] == candidates[startIndx] : |
| 23 | + endIndx += 1 |
| 24 | + |
| 25 | + for i in range(startIndx, endIndx) : |
| 26 | + if currTotal + candidates[currIndx] > target : |
| 27 | + break |
| 28 | + valsSoFar.append(candidates[currIndx]) |
| 29 | + currTotal += candidates[currIndx] |
| 30 | + helper(currTotal, endIndx, valsSoFar, output) |
| 31 | + |
| 32 | + # Remove the values since we're using the same valsSoFar pointer |
| 33 | + while valsSoFar and valsSoFar[-1] == candidates[currIndx] : |
| 34 | + currTotal -= valsSoFar.pop() |
| 35 | + |
| 36 | + currIndx = endIndx |
| 37 | + return output |
| 38 | + |
| 39 | + return helper() |
0 commit comments