Skip to content

Instantly share code, notes, and snippets.

@kflu
Created June 26, 2012 16:53
Show Gist options
  • Save kflu/2997094 to your computer and use it in GitHub Desktop.
Save kflu/2997094 to your computer and use it in GitHub Desktop.
Printing all possible permutations of valid parenthesis pairs
class PrintParenth:
def __init__(self, n):
self.n = n
self.s = [None for i in range(2*n)]
def P(self, l, r):
if l==self.n and r==self.n:
yield ''.join(self.s)
if l < self.n:
self.s[l+r] = '('
for s in self.P(l+1, r):yield s
if l > r:
self.s[l+r] = ')'
for s in self.P(l, r+1): yield s
def solve(self):
return self.P(0,0)
c = PrintParenth(4)
for s in c.solve():
print s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment