Created
June 26, 2012 16:53
-
-
Save kflu/2997094 to your computer and use it in GitHub Desktop.
Printing all possible permutations of valid parenthesis pairs
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
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