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

Function generate_parenthesis

backtracking/generate_parentheses.py:48–75  ·  view source on GitHub ↗

Generate valid combinations of balanced parentheses for a given n. :param n: An integer representing the number of pairs of parentheses. :return: A list of strings with valid combinations. This function uses a recursive approach to generate the combinations. Time Complexity:

(n: int)

Source from the content-addressed store, hash-verified

46
47
48def generate_parenthesis(n: int) -> list[str]:
49 """
50 Generate valid combinations of balanced parentheses for a given n.
51
52 :param n: An integer representing the number of pairs of parentheses.
53 :return: A list of strings with valid combinations.
54
55 This function uses a recursive approach to generate the combinations.
56
57 Time Complexity: O(2^(2n)) - In the worst case, we have 2^(2n) combinations.
58 Space Complexity: O(n) - where 'n' is the number of pairs.
59
60 Example 1:
61 >>> generate_parenthesis(3)
62 ['((()))', '(()())', '(())()', '()(())', '()()()']
63
64 Example 2:
65 >>> generate_parenthesis(1)
66 ['()']
67
68 Example 3:
69 >>> generate_parenthesis(0)
70 ['']
71 """
72
73 result: list[str] = []
74 backtrack("", 0, 0, n, result)
75 return result
76
77
78if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

backtrackFunction · 0.70

Tested by

no test coverage detected