简单的递归解释

时间:2012-05-01 17:03:24

标签: java recursion

这是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;
}

如果我们将方法调用为神秘(3,4),将打印到标准输出的内容是什么?什么是神秘召唤(3,4)的最终回报值?

标准输出部分答案的解释是什么。

输出:

0 1
1 4
2 16
3 64

最终返回值为64。

4 个答案:

答案 0 :(得分: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 :(得分: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;
       }
   }

希望这有帮助

答案 2 :(得分:1)

此示例计算m为幂n。 所以在你的情况下,值是64。

但是你有没有试过并做过你的分析?

答案 3 :(得分:0)

第一个电话是神秘的(3,4)然后称为神秘(2,4)然后称为神秘(1,4)然后称为神秘(0,4)。在这个例子中,基本情况是神秘的(0,4),即m> 1。 0计算结果为false,结果= n * mystery(m-1,n)将不会执行(递归终止于此处)。你的基础案例位于调用堆栈的顶部,堆栈的底部是神秘的(3,4)。从调用堆栈的顶部向底部进行评估...

enter image description here