Skip to content

add : to add generate_paranthese program under BACKTRACKING #9937

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 15 commits into from
Closed
Changes from 13 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
50 changes: 50 additions & 0 deletions backtracking/generate_parentheses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""
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[str]:
"""
>>> generate_parentheses(3)
['((()))', '(()())', '(())()', '()(())', '()()()']

>>> generate_parentheses(1)
['()']

>>> generate_parentheses(0)
['']
"""
def backtrack(parentheses : str = "",left : int = 0,right : int = 0) -> None:

if len(parentheses) == 2 * number:
result.append(parentheses)
return
if left < number:
backtrack(parentheses + "(", left + 1, right)
if right < left:
backtrack(parentheses + ")", left, right + 1)

result = []
backtrack()
return result

if __name__ == "__main__":
import doctest

doctest.testmod()
print(f"{generate_parentheses()}")