Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created January 22, 2020 18:21
Show Gist options
  • Save shailrshah/a4d6beaa122c09caa2a38f996004a667 to your computer and use it in GitHub Desktop.
Save shailrshah/a4d6beaa122c09caa2a38f996004a667 to your computer and use it in GitHub Desktop.
Return a unique list of strings each of length 2*n which have balanced paranthesis
from typing import List
def generate_all_paranthesis(n: int) -> List[str]:
'Return a unique list of strings each of length 2*n which have balanced paranthesis'
all_paranthesis = []
backtrack_helper(all_paranthesis, "", 0, 0, n)
return all_paranthesis
def backtrack_helper(all_paranthesis: List[str], curr_str: str, open: int, close: int, n: int) -> None:
"""
Backtracking helper for generate_all_paranthesis() which builds each string
and adds it to the given list when fully built.
"""
if len(curr_str) == 2*n:
all_paranthesis.append(curr_str)
if open < n:
backtrack_helper(all_paranthesis, curr_str + "(", open+1, close, n)
if close < open:
backtrack_helper(all_paranthesis, curr_str + ")", open, close+1, n)
assert generate_all_paranthesis(2) == ["(())", "()()"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment