Java 为什么不是';递归代码调用所有的案例?
我目前是学习递归的新手程序员,我不明白为什么我的代码不能工作。我必须编写一个名为waystogramb的递归方法,它输出不同的方法来爬升n步。你可以一步步爬上1到2级。以下是我到目前为止的情况:Java 为什么不是';递归代码调用所有的案例?,java,recursion,Java,Recursion,我目前是学习递归的新手程序员,我不明白为什么我的代码不能工作。我必须编写一个名为waystogramb的递归方法,它输出不同的方法来爬升n步。你可以一步步爬上1到2级。以下是我到目前为止的情况: public void waysToClimb(int n) { if (n == 0) { //base case, makes a new line for the next series of steps System.out.println(); } if (n &
public void waysToClimb(int n) {
if (n == 0) {
//base case, makes a new line for the next series of steps
System.out.println();
}
if (n >= 1) {
//1 step, prints 1 and subtracts 1 from n
System.out.print("1 ");
waysToClimb(n - 1);
}
if (n >= 2) {
//2 steps, prints 2 and subtracts 2 from n
System.out.print("2 ");
waysToClimb(n - 2);
}
}
我的问题是,当步数大于2时,whenn>=2
的if语句只输出2,而不输出其他数字。例如,案例WAYSTOGRIMP(3)打印出:
1 1 1
2 (should be 1 2)
2 1
为什么不打印出12个呢?如果我的if语句不应该打印出所有可能的组合,因为代码必须检查每一个组合标记代码并单步执行:
public void waysToClimb(int n) {
// #1
if (n == 0) {
//base case, makes a new line for the next series of steps
System.out.println();
}
// #2
if (n >= 1) {
//1 step, prints 1 and subtracts 1 from n
System.out.print("1 ");
waysToClimb(n - 1);
}
// #3
if (n >= 2) {
//2 steps, prints 2 and subtracts 2 from n
System.out.print("2 ");
waysToClimb(n - 2);
}
}
您的代码现在逐步执行的操作:
Call: IF: Print: Function call:
waysToClimb(3) #2 1 waysToClimb(2)
waysToClimb(2) #2 1 waysToClimb(1)
waysToClimb(1) #2 1 waysToClimb(0)
waysToClimb(0) #1 \n return
waysToClimb(2) #3 2 waysToClimb(0)
waysToClimb(0) #1 \n return
waysToClimb(3) #3 2 waysToClimb(1)
waysToClimb(1) #2 1 waysToClimb(0)
waysToClimb(0) #1 \n return
因此,输出为:
1 1 1
2
2 1
你应该做什么:
public void waysToClimb(int n, String s) {
if (n == 0) {
System.out.println(s);
}
if (n >= 1) {
waysToClimb(n - 1, s + "1 ");
}
if (n >= 2) {
waysToClimb(n - 2, s + "2 ");
}
}
使用以下命令调用函数:
waysToClimb(3, "");
调用堆栈是:
waysToClimb(3)
System.out.print("1 ")
waysToClimb(2)
System.out.print("1 ")
waysToClimb(1)
System.out.print("1 ")
waysToClimb(0)
System.out.println()
System.out.print("2 ")
waysToClimb(0)
System.out.println()
System.out.print("2 ")
waysToClimb(1)
System.out.print("1 ")
waysToClimb(0)
System.out.println()
你试过用调试器检查原因吗?哦。。。我想我明白了为什么它在完成第一次爬升(0)后2点开始。在第一个案例完成后,当它开始分解备份时,它会检查2>=2,并从那里开始,而不是从3开始。谢谢你的帮助。