|
| 1 | +""" |
| 2 | +the `helper()` check if the `target_remain` is 0. |
| 3 | +If true, it means that the sum of `combination` is equal to the `target`. Put the `combination` to the `answer`. |
| 4 | +If not, we For-loop each number, put it in the `combination` and try the `combination`. See if the number can make `target_remain` 0. |
| 5 | +
|
| 6 | +
|
| 7 | +The `start` means the `candidates[start:]` are the candidate we only need to concider. |
| 8 | +For example if |
| 9 | +``` |
| 10 | +candidates = [2,3,6,7], target = 7 |
| 11 | +``` |
| 12 | +If we pick 3, we are not allow to pick 2 any more, or we will have duplicate combination. |
| 13 | +We are only allow to pick the number at the same index or afterwards. |
| 14 | +
|
| 15 | +
|
| 16 | +So in the For-loop, if the smallest candidate is larger than the `target_remain`, we don't need to check afterwards. |
| 17 | +And that is why we need to sort the `candidates` in the first place. |
| 18 | +
|
| 19 | +``` |
| 20 | +candidates = [2,3,6,7] |
| 21 | +target = 7 |
| 22 | +
|
| 23 | +helper([], 0, 7) |
| 24 | + helper([2], 0, 5) |
| 25 | + helper([2, 2], 0, 3) |
| 26 | + helper([2, 2, 2], 0, 1) |
| 27 | + BREAK. When we are about to call helper([2, 2, 2, 2], 0, 1), we found that 2>target_remain. |
| 28 | +
|
| 29 | + helper([2, 2, 3], 1, 0) --> bingo |
| 30 | +
|
| 31 | + helper([2, 3], 1, 2) |
| 32 | + BREAK. When we are about to call helper([2, 6], 2, 2), we found that 6>target_remain. |
| 33 | +
|
| 34 | + helper([3], 1, 4) |
| 35 | + . |
| 36 | + . |
| 37 | + . |
| 38 | +
|
| 39 | + helper([6], 2, 1) |
| 40 | + . |
| 41 | + . |
| 42 | + . |
| 43 | +
|
| 44 | + helper([7], 3, 0) --> bingo |
| 45 | +
|
| 46 | +``` |
| 47 | +""" |
| 48 | +class Solution(object): |
| 49 | + def combinationSum(self, candidates, target): |
| 50 | + def helper(combination, start, target_remain): |
| 51 | + if target_remain==0: |
| 52 | + answer.append(combination) |
| 53 | + for i in xrange(start, len(candidates)): |
| 54 | + n = candidates[i] |
| 55 | + if n>target_remain: break |
| 56 | + helper(combination+[n], i, target_remain-n) |
| 57 | + |
| 58 | + candidates.sort() |
| 59 | + answer = [] |
| 60 | + helper([], 0, target) |
| 61 | + return answer |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +#Old Solution |
| 66 | +class Solution(object): |
| 67 | + def combinationSum(self, candidates, target): |
| 68 | + def helper(candidates, target, combination): |
| 69 | + if not candidates: return [] |
| 70 | + n = candidates[0] |
| 71 | + if n>target: |
| 72 | + return [] |
| 73 | + elif n==target: |
| 74 | + return [combination+[n]] |
| 75 | + else: |
| 76 | + return helper(candidates, target-n, combination+[n]) + helper(candidates[1:], target, combination) |
| 77 | + return helper(sorted(candidates), target, []) |
0 commit comments