forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_parenthesis.py
48 lines (44 loc) · 906 Bytes
/
generate_parenthesis.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
"""
Given 'n' Pairs of parenthesis,
this program generates all combinations of parenthesis
Example, n=3 :
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
This problem is solved using Backtracking
"""
def solve(op,open,close, ans):
if(open == 0 and close == 0):
ans.append(op)
return
if(open == close):
op1 = op
op1+=('(')
solve(op1, open-1, close, ans)
elif(open == 0):
op1 = op
op1+=(')')
solve(op1, open, close-1, ans)
elif(close == 0):
op1 = op
op1+=('(')
solve(op1, open-1, close, ans)
else:
op1 = op
op2 = op
op1+=('(')
op2+=(')')
solve(op1, open-1, close, ans)
solve(op2, open, close-1, ans)
def generate_parenthesis(n):
open = n
close = n
ans=[]
op = ""
solve(op, open, close, ans)
return ans
print(generate_parenthesis(3))