MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / combination_sum

Function combination_sum

backtracking/combination_sum.py:41–65  ·  view source on GitHub ↗

>>> 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)

Source from the content-addressed store, hash-verified

39
40
41def 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
68def main() -> None:

Callers 1

mainFunction · 0.85

Calls 1

backtrackFunction · 0.70

Tested by

no test coverage detected