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

Function backtrack

backtracking/generate_parentheses.py:11–45  ·  view source on GitHub ↗

Generate valid combinations of balanced parentheses using recursion. :param partial: A string representing the current combination. :param open_count: An integer representing the count of open parentheses. :param close_count: An integer representing the count of close parentheses.

(
    partial: str, open_count: int, close_count: int, n: int, result: list[str]
)

Source from the content-addressed store, hash-verified

9
10
11def backtrack(
12 partial: str, open_count: int, close_count: int, n: int, result: list[str]
13) -> None:
14 """
15 Generate valid combinations of balanced parentheses using recursion.
16
17 :param partial: A string representing the current combination.
18 :param open_count: An integer representing the count of open parentheses.
19 :param close_count: An integer representing the count of close parentheses.
20 :param n: An integer representing the total number of pairs.
21 :param result: A list to store valid combinations.
22 :return: None
23
24 This function uses recursion to explore all possible combinations,
25 ensuring that at each step, the parentheses remain balanced.
26
27 Example:
28 >>> result = []
29 >>> backtrack("", 0, 0, 2, result)
30 >>> result
31 ['(())', '()()']
32 """
33 if len(partial) == 2 * n:
34 # When the combination is complete, add it to the result.
35 result.append(partial)
36 return
37
38 if open_count < n:
39 # If we can add an open parenthesis, do so, and recurse.
40 backtrack(partial + "(", open_count + 1, close_count, n, result)
41
42 if close_count < open_count:
43 # If we can add a close parenthesis (it won't make the combination invalid),
44 # do so, and recurse.
45 backtrack(partial + ")", open_count, close_count + 1, n, result)
46
47
48def generate_parenthesis(n: int) -> list[str]:

Callers 1

generate_parenthesisFunction · 0.70

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected