繁体   English   中英

简单的递归解释

[英]Simple Recursion Explanation

这是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。

考虑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)一个封闭的表格吗?

鉴于你的代码

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

希望这可以帮助

该样本计算m为幂n。 所以在你的情况下,值为64。

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

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

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM