# Time complexity for combination of parentheses

Staff member
I tried to do the classical problem to implement an algorithm to print all valid combinations of n pairs of parentheses.

I found this program (which works perfectly) :

Code:
``````public static void addParen(ArrayList&lt;String&gt; list, int leftRem, int rightRem, char[] str, int count) {
if (leftRem &lt; 0 || rightRem &lt; leftRem) return; // invalid state

if (leftRem == 0 &amp;&amp; rightRem == 0) { /* all out of left and right parentheses */
String s = String.copyValueOf(str);
} else {
if (leftRem &gt; 0) { // try a left paren, if there are some available
str[count] = '(';
addParen(list, leftRem - 1, rightRem, str, count + 1);
}
if (rightRem &gt; leftRem) { // try a right paren, if there’s a matching left
str[count] = ')';
addParen(list, leftRem, rightRem - 1, str, count + 1);
}
}
}

public static ArrayList&lt;String&gt; generateParens(int count) {
char[] str = new char[count*2];
ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();