So I have this problem. I was trying to code a program to print all the valid possible arrangements of brackets i.e. for 3 brackets we can have ((())), (()()), ()()(), (())() etc.
I have a working code
public static void main(String[] args) {
int number = 3; // No. of brackets
int cn = number;
int on = number;
// open and closed brackets respectively
char[] sol = new char[6];
printSol(on, cn, sol, 0);
}
public static void printSol(int cn, int on, char[] sol, int k) {
if (on == 0 && cn == 0) {
System.out.println("");
for (int i = 0; i < 6; i++) {
System.out.print(sol[i]);
}
}
else {
if (on > 0) {
if (cn > 0) {
sol[k] = '(';
printSol(on - 1, cn, sol, k + 1);
}
}
if (cn > on) {
sol[k] = ')';
printSol(on, cn - 1, sol, k + 1);
}
}
}
Now the problem is that I want to do this using ArrayList instead of using char array. I tried but am getting errors. If anyone has any suggestions please let me know. The main purpose of asking this question is that I want to know when shall I prefer ArrayLists over arrays in Recursion problems.
P.S. I am sorry for the poor indentation as I had to type the whole program due to surfing restrictions and also thre might be some syntax errors but I tried my best. Thanks Mohit