2015-08-19 72 views
0

我目前是學習遞歸的新手程序員,我不明白爲什麼我的代碼不工作。我必須編寫一個稱爲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語句我打印出所有可能的組合,因爲代碼將被強制檢查每一個

+2

您是否嘗試過使用調試器來檢查,爲什麼? – Aify

回答

2

標註你的代碼,並加強其通過:

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, ""); 
+0

噢......我想我明白了爲什麼它在第一個waysToClimb(0)完成後從2開始。在第一個案例完成後,當它開始解散備份時,它會檢查2> = 2並從那裏開始,而不是3.感謝您的幫助。 –

0

調用堆棧是:

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() 
相關問題