我正在编写一个没有查看答案的编码问题,我正在努力找到我的思维过程中的错误
问题是找到有效n对括号的所有组合
public class Foo{
public void printCombinations(String prefix, int open, int close, int n){
if (open > n) {
return;
}
if (close > n) {
return;
}
if (open == n && close == n){
System.out.println(prefix);
return;
}
printCombinations(prefix + "(", open + 1, close, n);
printCombinations(prefix + ")", open, close + 1, n);
}
public static void main(String []args){
HelloWorld w = new HelloWorld();
w.printCombinations("", 0, 0, 3);
}
}
当我运行这个程序时,似乎打印出所有组合而不是有效括号的组合。我在想printCombinations(prefix + "(", open + 1, close, n);
会确保我首先打印左括号然后递归调用printCombinations(prefix + ")", open, close + 1, n);
我看到一个类似)))(((
的输出。如果首先添加(
,这怎么可能?
答案 0 :(得分:0)
它是因为在堆栈上完成printCombinations(prefix + "(", open + 1, close, n)
的递归调用后,您的代码开始重现printCombinations(prefix + ")", open, close + 1, n)
。这就是为什么你会得到一个以)
开头的字符串输出,而不是因为你放置这两个递归调用的顺序。要解决此问题,您需要具备close
始终小于open
的条件。如下,
public class Foo{
public void printCombinations(String prefix, int open, int close, int n){
if (open > n) {
return;
}
if (close > n) {
return;
}
if (open == n && close == n){
System.out.println(prefix);
return;
}
printCombinations(prefix + "(", open + 1, close, n);
if (close < open) {
printCombinations(prefix + ")", open, close + 1, n);
}
}
public static void main(String []args){
Foo w = new Foo();
w.printCombinations("", 0, 0, 3);
}
}