Skip to content

Instantly share code, notes, and snippets.

@vetional
Created November 21, 2017 07:27
Show Gist options
  • Save vetional/12a07eec7a834e7406ebc26b7a7b41a5 to your computer and use it in GitHub Desktop.
Save vetional/12a07eec7a834e7406ebc26b7a7b41a5 to your computer and use it in GitHub Desktop.
balanced parentheses created by vetional - https://repl.it/@vetional/balanced-parentheses
# Print all possible n pairs of balanced parentheses.
# For example, when n is 2, the function should print “(())” and “()()”.
# When n is 3, we should get “((()))”, “(()())”, “(())()”, “()(())”, “()()()”.
def fn(l,r):
#print ('call : fn(' + str(l) + ',' + str(r) + ')')
if l < 0 or r < 0 or l > r:
return 0
if l == 0 and r == 0:
return 1
if l < r:
#print ('doing : fn(' + str(l-1) + ',' + str(r) + ') + fn(' + str(l) + ',' + str(r-1) + ')')
ways = fn(l-1,r) + fn(l,r-1)
else:
#print ('doing : fn(' + str(l-1) + ',' + str(r) + ')')
ways = fn(l-1, r)
return ways
print (fn(5,5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment