Skip to content

Commit f5f5dec

Browse files
committed
to add generate_par.py
1 parent 795e97e commit f5f5dec

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

backtracking/generate_parentheses.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
Given 'n' pairs of parentheses,
3+
this program generates all combinations of parentheses.
4+
Example, n = 3 :
5+
[
6+
"((()))",
7+
"(()())",
8+
"(())()",
9+
"()(())",
10+
"()()()"
11+
]
12+
This problem can be solved using the concept of "BACKTRACKING".
13+
By adding an open parenthesis to the solution and
14+
recursively add more till we get 'n' open parentheses.
15+
Then we start adding close parentheses until the solution is valid
16+
(open parenthesis is closed).
17+
If we reach a point where we can not add more parentheses to the solution,
18+
we backtrack to the previous step and try a different path.
19+
"""
20+
21+
def generate_parentheses(number : int = 0) -> list:
22+
"""
23+
>>> generate_parentheses(3)
24+
['((()))', '(()())', '(())()', '()(())', '()()()']
25+
26+
>>> generate_parentheses(1)
27+
['()']
28+
29+
>>> generate_parentheses(0)
30+
['']
31+
"""
32+
def backtrack(x : str = "",left : int = 0,right : int = 0) -> None:
33+
34+
if len(x) == 2 * number:
35+
result.append(x)
36+
return
37+
if left < number:
38+
backtrack(x + "(", left + 1, right)
39+
if right < left:
40+
backtrack(x + ")", left, right + 1)
41+
42+
result = []
43+
backtrack()
44+
return result
45+
46+
if __name__ == "__main__":
47+
import doctest
48+
49+
doctest.testmod()
50+
print(f"{generate_parentheses()}")

0 commit comments

Comments
 (0)