【发布时间】:2011-04-22 09:19:35
【问题描述】:
所以我有这个问题。我试图编写一个程序来打印括号的所有有效可能排列,即我们可以有 3 个括号 ((()))、(()())、()()()、(())()等等
我有一个工作代码
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);
}
}
}
现在的问题是我想使用 ArrayList 而不是 char 数组来执行此操作。 我尝试过,但出现错误。如果有人有任何建议,请告诉我。问这个问题的主要目的是我想知道在递归问题中我什么时候更喜欢 ArrayLists 而不是数组。
附: 我很抱歉缩进不佳,因为由于冲浪限制,我不得不输入整个程序,并且可能存在一些语法错误,但我已尽力而为。 谢谢 莫希特
【问题讨论】:
-
感谢您为我缩进
-
您在尝试 ArrayList 时遇到了哪些错误?知道这一点会更容易找到问题。
-
请具体说明您遇到的错误 - 编译、运行时、测试失败还是...?一般来说,您的问题越详细、越准确,您获得的帮助就越大……
标签: java arrays recursion arraylist