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

Function backtrack

backtracking/combination_sum.py:16–38  ·  view source on GitHub ↗

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
)

Source from the content-addressed store, hash-verified

14
15
16def 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
41def combination_sum(candidates: list, target: int) -> list:

Callers 1

combination_sumFunction · 0.70

Calls 3

copyMethod · 0.80
appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected