2012-05-01 203 views
3

這是Java中的遞歸靜態方法。簡單遞歸說明

public static int mystery(int m, int n) { 
    int result = 1; 

    if (m > 0) { 
     result = n * mystery(m-1, n); 
    }  

    System.out.println (m + " " + result); 
    return result; 
} 

如果我們使方法調用mystery(3,4),將打印到標準輸出上的內容是什麼?呼叫到神祕(3,4)的最終回報價值是多少?

標準輸出部分答案的解釋是什麼?

輸出:

0 1 
1 4 
2 16 
3 64 

最終返回值是64。

+3

你有什麼想法這麼遠? –

+0

這是你的作業嗎? – bfontaine

+1

不,我想通過這個例子瞭解遞歸 – JavaStudent12344

回答

5

考慮n被固定(這對於所有意圖和目的是),並讓f(m)mystery(m,n)

然後

f(0) = 1 
f(1) = n * f(0) = n 
f(2) = n * f(1) = n * n 
f(3) = n * f(2) = n * n * n 

你能看到的一般模式?你可以給f(n)關閉表格嗎?

1

這個例子計算m的功率n。 所以在你的情況下,這個值是64.

但是你有沒有嘗試過,並做過你的部分分析?

2

鑑於你的代碼是

public static int mystery(int m, int n) { 
int result = 1; 

if (m > 0) { 
    result = n * mystery(m-1, n); 
}  

System.out.println (m + " " + result); 
return result; 
} 

讓我們開始用M = 3和n = 4,讓我們試着通過努力成爲調試器來模擬它...

mystery(3,4){ 
    int result = 1 
    if(3 > 0){ 
     result = 4 * mystery(3-1,4); 
     //We proceed from this point only after evaluating mystery(2,4) 
     mystery(2,4){ 
      int result = 1 
      if(2 > 0){ 
       result = 4*mystery(2-1,4); 
       //Now we have to evaluate mystery(1,4) 
       mystery(1,4){ 
        int result = 1; 
         if(1 > 0){ 
          result = 4*mystery(1-1,4); 
          //Evaluate mystery(0,4) 
          mystery(0,4){ 
          int result = 1; 
          if(0 > 0){ 
           //Not evaluated 
          } 
          System.out.println(0 + " "+1); 
          return 1; 
          }...mystery(0,4) done continue with evaluation of mystery(1,4) 
          result = 4*1 //1 is what is returned by mystery(0,4) 
          System.out.println(1+ "" + 4); 
          return 4; 
         }//done with the evaluation of mystery(1,4), resume evaluation of mystery(2,4) 
       result = 4*4 //4 is the value returned by mystery(1,4) 
       System.out.println(2 + " " + 16); 
       return 16;    
       }//At this point we are done with evaluating (2,4) and on the way to resume evaluation of mystery(3,4) 
     result = 4 * 16 
     System.out.println(3 + " "+ 64) 
     return 64; 
     } 
    } 

希望這幫助

0

第一個電話是神祕(3,4)然後調用神祕(2,4),然後調用神祕(1,4),然後調用神祕(0,4)。在這個例子中,基本情況是神祕的(0,4),即m> 0的計算結果爲false,並且result = n * mystery(m-1,n)不會被執行(遞歸在此終止)。你的基本情況在調用堆棧之上,你的堆棧底部是神祕的(3,4)。從向底部調用堆棧的頂部評估...

enter image description here