Created
September 13, 2021 19:20
-
-
Save les-peters/e1f6dbfd70628b37f65c9197ba2fb818 to your computer and use it in GitHub Desktop.
Parentheses Pairs
This file contains 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
question = """ | |
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. | |
Example: | |
$ formParens(1) | |
$ ["()"] | |
$ formParens(3) | |
$ ["((()))","(()())","(())()","()(())","()()()"] | |
""" | |
def formParens(n): | |
paren_array_keys = {} | |
paren_array = [] | |
if n == 1: | |
return [ "()" ] | |
if n > 1: | |
lower_set = formParens(n - 1) | |
for set in lower_set: | |
prepend_set = '()' + set | |
append_set = set + '()' | |
encase_set = '(' + set + ')' | |
paren_array_keys[prepend_set] = 1 | |
paren_array_keys[append_set] = 1 | |
paren_array_keys[encase_set] = 1 | |
for key in paren_array_keys.keys(): | |
paren_array.append(key) | |
return paren_array | |
print(formParens(1)) | |
print(formParens(3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to you!
Yes, you got it! 👏 Congrats!