>>> combination_sum([2, 3, 5], 8) [[2, 2, 2, 2], [2, 3, 3], [3, 5]] >>> combination_sum([2, 3, 6, 7], 7) [[2, 2, 3], [7]] >>> combination_sum([-8, 2.3, 0], 1) Traceback (most recent call last): ... ValueError: All elements in candidates must be non-negative >
(candidates: list, target: int)
| 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 | ValueError: All elements in candidates must be non-negative |
| 51 | >>> combination_sum([], 1) |
| 52 | Traceback (most recent call last): |
| 53 | ... |
| 54 | ValueError: Candidates list should not be empty |
| 55 | """ |
| 56 | if not candidates: |
| 57 | raise ValueError("Candidates list should not be empty") |
| 58 | |
| 59 | if any(x < 0 for x in candidates): |
| 60 | raise ValueError("All elements in candidates must be non-negative") |
| 61 | |
| 62 | path = [] # type: list[int] |
| 63 | answer = [] # type: list[int] |
| 64 | backtrack(candidates, path, answer, target, 0) |
| 65 | return answer |
| 66 | |
| 67 | |
| 68 | def main() -> None: |