Created
November 20, 2010 03:03
-
-
Save lonnen/707568 to your computer and use it in GitHub Desktop.
Prints all sets of nested parenthesis of order [number] using dynamic programming.
This file contains 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
''' | |
Prints all sets of nested parenthesis of order [number] | |
Usage: python printKParens.py number | |
''' | |
import sys | |
def printKParens(s, index, k_remaining): | |
if(index == len(s)): | |
print ''.join(s) | |
return | |
if k_remaining: | |
s[index] = "(" | |
printKParens(s, index+1, k_remaining-1) | |
if k_remaining < ((len(s)-index)/2.0): # python 2.X has screwy division | |
s[index] = ")" | |
printKParens(s, index+1, k_remaining) | |
else: | |
s[index] = ")" | |
printKParens(s, index+1, k_remaining) | |
if __name__ == '__main__': | |
try: | |
print "Generating all trees of " + sys.argv[1] + " nested parens." | |
except IndexError: | |
print __doc__ | |
sys.exit(1) | |
printKParens([")" for x in range(2*int(sys.argv[1]))], 0, int(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment