Recursive solution is based on constraint that number of left open parentheses should be greater than right closing.
Following code appends parentheses from the left to the right with such constraint:
def gen_aux(left, right, result): if left == 0 and right == 0: print(result) return if left > 0: gen_aux(left-1, right, result+"(") if right > left: gen_aux(left, right-1, result+")") def gen(n): gen_aux(n, n, "")
Result of:
gen(1) gen(2) gen(3) gen(4)
is:
() (()) ()() ((())) (()()) (())() ()(()) ()()() (((()))) ((()())) ((())()) ((()))() (()(())) (()()()) (()())() (())(()) (())()() ()((())) ()(()()) ()(())() ()()(()) ()()()()