The python code generates balanced parenthesis recursively. Example for depth=3 i.e. 3 opening brackets and 3 closing brackets,the sample output should be:
((())) (()()) (())() ()(()) ()()()
The number of such output ( 5 in above case) is a Catalan Number.
1 2 3 4 5 6 7 8
def pargen(left,right,ans): if(left==0 and right==0): print ans; if(left>0): pargen(left-1,right+1,ans+'('); if(right>0): pargen(left,right-1,ans+')'); pargen(3,0,''); #can pass any starting value as left,initial value of right is always 0.