2012-05-01 204 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