首页 > 解决方案 > 不知道这个方法是做什么的

问题描述

我对 return 语句的作用感到困惑。它是在方法内部执行该方法还是增加了一些东西?

 public int recur(int n)
 {
    if (n <= 10)
        return n*2;
    else
        return recur(recur(n/3));
 }

标签: java

解决方案


return语句将向调用者提供结果。如果调用者调用自己,堆栈上的新框架将为这个新调用构建。当堆栈上的最后一帧返回值时,程序退出。

为了追踪这一点,我们假设最初的调用是recur(15),我们20从 A 得到如下。A、B 和 C 是用于程序执行的堆栈帧。

A: recur(15) -> recur(recur(15/3)) -> Go to B -> When B has returned -> Go to C -> When C has returned, A will return 20.
A is gone now, and program exits.

===============================================

B: recur(15/3) i.e. recur(5)
Note that this is the inner recur()
Now, we hit the base case of n <= 10
n * 2 = 5 * 2 = 10 returned to A
B is gone now

===============================================

C: recur(10)
Now, we again hit the base case of n <= 10
Note that this is the outer recur()
n * 2 = 10 * 2 = 20 returned to A
C is gone now

尾递归是一种优化,如果递归调用是方法中的最后一行,它将使用相同的帧代替单独的帧。但是上面的逻辑通常可以用来理解递归。


推荐阅读