Skip to content

Added generate parenthesis algorithm #10068

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 17 commits into from
Closed
Changes from 16 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
43 changes: 43 additions & 0 deletions backtracking/generate_parenthesis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import doctest

def solve(op: str, open: int, close: int, ans: list[str]) -> None:
if open == 0 and close == 0:
ans.append(op)
return
if open == close:
op1: str = op
op1 += "("
solve(op1, open - 1, close, ans)
elif open == 0:
op1: str = op
op1 += ")"
solve(op1, open, close - 1, ans)
elif close == 0:
op1: str = op
op1 += "("
solve(op1, open - 1, close, ans)
else:
op1: str = op
op2: str = op
op1 += "("
op2 += ")"
solve(op1, open - 1, close, ans)
solve(op2, open, close - 1, ans)


def generate_parenthesis(n: int) -> list[str]: # n = no. of pairs of parenthesis > 0
"""
>>> generate_parenthesis(3)
['((()))', '(()())', '(())()', '()(())', '()()()']
>>> generate_parenthesis(4)
['(((())))', '((()()))', '((())())', '((()))()', '(()(()))', '(()()())', '(()())()', '(())(())', '(())()()', '()((()))', '()(()())', '()(())()', '()()(())', '()()()()']
"""
open: int = n
close: int = n
ans: list[str] = []
op: str = ""
solve(op, open, close, ans)
if n > 0:
return ans

doctest.testmod()