Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created September 13, 2021 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save les-peters/e1f6dbfd70628b37f65c9197ba2fb818 to your computer and use it in GitHub Desktop.
Save les-peters/e1f6dbfd70628b37f65c9197ba2fb818 to your computer and use it in GitHub Desktop.
Parentheses Pairs
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))
@rachelcarmena
Copy link

Hi!

Just leaving a comment in case it's useful for you 🙌

I tried a similar approach, however I discarded because I missed some options.

I think it works for 1, 2 and 3 pairs. However, formParens(4) doesn't show:

(())(())

formParens(5) doesn't show:

((())(()))
((()))(())
(()())(())
(())((()))
(())(()())
(())(())()
(())()(())
()(())(())

formParens(6) doesn't show:

(((())(())))
(((()))(()))
(((())))(())
((()())(()))
((()()))(())
((())((())))
((())(()()))
((())(())())
((())(()))()
((())()(()))
((())())(())
((()))((()))
((()))(()())
((()))(())()
((()))()(())
(()(())(()))
(()(()))(())
(()()())(())
(()())((()))
(()())(()())
(()())(())()
(()())()(())
(())(((())))
(())((()()))
(())((())())
(())((()))()
(())(()(()))
(())(()()())
(())(()())()
(())(())(())
(())(())()()
(())()((()))
(())()(()())
(())()(())()
(())()()(())
()((())(()))
()((()))(())
()(()())(())
()(())((()))
()(())(()())
()(())(())()
()(())()(())
()()(())(())

Kind regards!

@les-peters
Copy link
Author

les-peters commented Sep 20, 2021 via email

@rachelcarmena
Copy link

Thank you very much

Thanks to you!

Here is a change that seems to help:

Yes, you got it! 👏 Congrats!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment