A recursive function that searches for possible combinations. Backtracks in case of a bigger current combination value than the target value. Parameters ---------- previous_index: Last index from the previous search target: The value we need to obtain by summing our integer
(
candidates: list, path: list, answer: list, target: int, previous_index: int
)
| 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: |
no test coverage detected