-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
/
Copy pathgenerate_parentheses.py
52 lines (43 loc) · 1.28 KB
/
generate_parentheses.py
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
"""
Given 'n' pairs of parentheses,
this program generates all combinations of parentheses.
Example, n = 3 :
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
This problem can be solved using the concept of "BACKTRACKING".
By adding an open parenthesis to the solution and
recursively add more till we get 'n' open parentheses.
Then we start adding close parentheses until the solution is valid
(open parenthesis is closed).
If we reach a point where we can not add more parentheses to the solution,
we backtrack to the previous step and try a different path.
"""
def generate_parentheses(number: int = 0) -> list:
"""
>>> generate_parentheses(3)
['((()))', '(()())', '(())()', '()(())', '()()()']
>>> generate_parentheses(1)
['()']
>>> generate_parentheses(0)
['']
"""
def backtrack(x : str = "",left : int = 0,right : int = 0) -> None:
if len(x) == 2 * number:
result.append(x)
return
if left < number:
backtrack(parantheses + "(", left + 1, right)
if right < left:
backtrack(parantheses + ")", left, right + 1)
result = []
backtrack()
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"{generate_parentheses()}")