|
| 1 | +""" |
| 2 | +In the Combination Sum problem, we are given a list consisting of distinct integers. |
| 3 | +We need to find all the combinations whose sum equals to target given. |
| 4 | +We can use an element more than one. |
| 5 | +
|
| 6 | +Time complexity(Average Case): O(n!) |
| 7 | +
|
| 8 | +Constraints: |
| 9 | +1 <= candidates.length <= 30 |
| 10 | +2 <= candidates[i] <= 40 |
| 11 | +All elements of candidates are distinct. |
| 12 | +1 <= target <= 40 |
| 13 | +""" |
| 14 | + |
| 15 | + |
| 16 | +def backtrack( |
| 17 | + candidates: list, path: list, answer: list, target: int, previous_index: int |
| 18 | +) -> None: |
| 19 | + """ |
| 20 | + A recursive function that searches for possible combinations. Backtracks in case |
| 21 | + of a bigger current combination value than the target value. |
| 22 | +
|
| 23 | + Parameters |
| 24 | + ---------- |
| 25 | + previous_index: Last index from the previous search |
| 26 | + target: The value we need to obtain by summing our integers in the path list. |
| 27 | + answer: A list of possible combinations |
| 28 | + path: Current combination |
| 29 | + candidates: A list of integers we can use. |
| 30 | + """ |
| 31 | + if target == 0: |
| 32 | + answer.append(path.copy()) |
| 33 | + else: |
| 34 | + for index in range(previous_index, len(candidates)): |
| 35 | + if target >= candidates[index]: |
| 36 | + path.append(candidates[index]) |
| 37 | + backtrack(candidates, path, answer, target - candidates[index], index) |
| 38 | + path.pop(len(path) - 1) |
| 39 | + |
| 40 | + |
| 41 | +def combination_sum(candidates: list, target: int) -> list: |
| 42 | + """ |
| 43 | + >>> combination_sum([2, 3, 5], 8) |
| 44 | + [[2, 2, 2, 2], [2, 3, 3], [3, 5]] |
| 45 | + >>> combination_sum([2, 3, 6, 7], 7) |
| 46 | + [[2, 2, 3], [7]] |
| 47 | + >>> combination_sum([-8, 2.3, 0], 1) |
| 48 | + Traceback (most recent call last): |
| 49 | + ... |
| 50 | + RecursionError: maximum recursion depth exceeded in comparison |
| 51 | + """ |
| 52 | + path = [] # type: list[int] |
| 53 | + answer = [] # type: list[int] |
| 54 | + backtrack(candidates, path, answer, target, 0) |
| 55 | + return answer |
| 56 | + |
| 57 | + |
| 58 | +def main() -> None: |
| 59 | + print(combination_sum([-8, 2.3, 0], 1)) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + import doctest |
| 64 | + |
| 65 | + doctest.testmod() |
| 66 | + main() |
0 commit comments