Skip to content

Added generate parenthesis algorithm #10066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions backtracking/generate_parenthesis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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))