Last active
April 12, 2016 02:32
-
-
Save travisofthenorth/90d116b387ddf657ce8fd0871bd95d26 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
# Print all combinations of balanced parentheses of length n | |
def recurse(str:, open:, closed:, n:) | |
if open + closed == n - 1 | |
str += ')' | |
p str | |
else | |
if open < n / 2 | |
recurse(str: str + '(', open: open + 1, closed: closed, n: n) | |
end | |
if closed < open | |
recurse(str: str + ')', open: open, closed: closed + 1, n: n) | |
end | |
end | |
end | |
def parens(n) | |
if n < 2 || n % 2 != 0 | |
raise 'Must be an even number greater than 0!' | |
end | |
recurse(str: '(', open: 1, closed: 0, n: n) | |
end | |
parens(ARGV[0].to_i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment