我目前是學習遞歸的新手程序員,我不明白爲什麼我的代碼不工作。我必須編寫一個稱爲waysToClimb的遞歸方法,它會輸出不同的方法來爬n步。你可以在1步上升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 >= 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,if語句的時候n >= 2
僅輸出2,但沒有其他號碼。例如,案例waysToClimb(3)打印出:
1 1 1
2 (should be 1 2)
2 1
爲什麼不打印出1 2?應該不是if語句我打印出所有可能的組合,因爲代碼將被強制檢查每一個
您是否嘗試過使用調試器來檢查,爲什麼? – Aify