-
-
Notifications
You must be signed in to change notification settings - Fork 50.5k
Expand file tree
/
Copy pathcombination_sum_2.py
More file actions
81 lines (66 loc) · 2.45 KB
/
combination_sum_2.py
File metadata and controls
81 lines (66 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""
In this Combination Problem, we are given a list consisting of distinct integers.
We need to find all the combinations whose sum equals to target given.
We cannot use an element more than one.
Time complexity(Average Case): O(n * 2^(n/2))
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
"""
def backtrack(candidates: list, target: int, start_index: int, total: int, path: list, answer: list) -> None:
"""
A recursive function that searches for possible combinations. Backtracks in case
of a bigger current combination value than the target value and removes the already
appended values for removing repetition of elements in the solutions.
Parameters
----------
start_index: Last index from the previous search
target: The value we need to obtain by summing our integers in the path list.
answer: A list of possible combinations
path: Current combination
candidates: A list of integers we can use.
total: Sum of elements in path
"""
if target == 0:
answer.append(path.copy())
return
if total == target:
answer.append(path.copy())
return
for i in range(start_index, len(candidates)):
if i > start_index and candidates[i] == candidates[i - 1]:
continue
if total + candidates[i] > target:
break
backtrack(candidates, target, i + 1, total + candidates[i], path + [candidates[i]], answer)
def combination_sum_2(candidates: list,target: int) -> list:
"""
>>> combination_sum_2([10,1,2,7,6,1,5], 8)
[[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
>>> combination_sum_2([1,2], 2)
[[2]]
>>> combination_sum_2([-8, 2.3, 0], 1)
Traceback (most recent call last):
...
ValueError: All elements in candidates must be non-negative
>>> combination_sum_2([], 1)
Traceback (most recent call last):
...
ValueError: Candidates list should not be empty
"""
if not candidates:
raise ValueError("Candidates list should not be empty")
if any(x < 0 for x in candidates):
raise ValueError("All elements in candidates must be non-negative")
candidates.sort()
path = []
answer = []
backtrack(candidates, target, 0, 0, path, answer)
return answer
def main() -> None:
print(combination_sum_2([-8, 2.3, 0], 1))
if __name__ == "__main__":
import doctest
doctest.testmod()
main()