How to print all possible balanced parentheses for an expression?

Here is actual code in Python, using generators to avoid using too much memory. #! /usr/bin/python def parenthesized (exprs): if len(exprs) == 1: yield exprs[0] else: first_exprs = [] last_exprs = list(exprs) while 1 < len(last_exprs): first_exprs.append(last_exprs.pop(0)) for x in parenthesized(first_exprs): if 1 < len(first_exprs): x = ‘(%s)’ % x for y in parenthesized(last_exprs): if … Read more

Finding all combinations of well-formed brackets

Took a crack at it.. C# also. public void Brackets(int n) { for (int i = 1; i <= n; i++) { Brackets(“”, 0, 0, i); } } private void Brackets(string output, int open, int close, int pairs) { if((open==pairs)&&(close==pairs)) { Console.WriteLine(output); } else { if(open<pairs) Brackets(output + “(“, open+1, close, pairs); if(close<open) Brackets(output + … Read more