I did write a code to print all valid combinations of n-pair parentheses. However, at my first try, the algorithm output all the combinations twice, that is, . The code was:
public static void solve(char[] string, int open, int closed, int index)
{
if (open < 0 || closed < open) {
return;
}
if (open == 0 && closed == 0) {
System.out.println(string);
}
if (open > 0) {
string[index] = '(';
solve(string, --open, closed, ++index);
}
if (closed > open) {
string[index] = ')';
solve(string, open, --closed, ++index);
}
}
I spend a significant amount of time in order to see what went wrong. I figured the code went into the last if branch more than it should. Then, while trying different things, I realized changing
solve(string, --open, closed, ++index);
to
solve(string, open-1, closed, ++index);
changed the outcome. This resulted in getting a java.lang.ArrayIndexOutOfBoundsException
. Finally, I replaced all pre-increment operations with corresponding arithmetic operations(e.g., ++index
to index+1
) and the code ran correctly.
My question is, shouldn't --open
and open-1
calculate and send the same value as parameter to the function? How come the code behaves differently when they should calculate the same value?