Created
January 22, 2020 18:21
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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