Last active
August 29, 2015 14:18
-
-
Save jordanlewis/528580c72e3856a2152d to your computer and use it in GitHub Desktop.
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
def generate_parens(n): | |
# this is a map from (n_unclosed, n_left) to result. | |
results = {} | |
def _generate_parens(n_unclosed, n_left): | |
# if we have a memoized value already, use it | |
already_computed = results.get((n_unclosed, n_left), None) | |
if already_computed is not None: | |
return already_computed | |
# This function returns a list of all possibilities given its inputs. | |
if n_left == 0: | |
# if we don't have any )'s left, generate as many ) as we need | |
return [ ")" * n_unclosed ] | |
# prepend a ( to every result of the recursive call | |
result = ["(" + x for x in _generate_parens(n_unclosed + 1, n_left - 1)] | |
if n_unclosed > 0: | |
# if we can close any, prepend a ) to every result. | |
result.extend([")" + x for x in _generate_parens(n_unclosed - 1, n_left)]) | |
# memoize the result | |
results[(n_unclosed, n_left)] = result | |
return result | |
return _generate_parens(0, n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment