Skip to content

Instantly share code, notes, and snippets.

@travisofthenorth
Last active April 12, 2016 02:32
Show Gist options
  • Save travisofthenorth/90d116b387ddf657ce8fd0871bd95d26 to your computer and use it in GitHub Desktop.
Save travisofthenorth/90d116b387ddf657ce8fd0871bd95d26 to your computer and use it in GitHub Desktop.
# 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