java - 不知道这个方法是做什么的
问题描述
我对 return 语句的作用感到困惑。它是在方法内部执行该方法还是增加了一些东西?
public int recur(int n)
{
if (n <= 10)
return n*2;
else
return recur(recur(n/3));
}
解决方案
该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
尾递归是一种优化,如果递归调用是方法中的最后一行,它将使用相同的帧代替单独的帧。但是上面的逻辑通常可以用来理解递归。
推荐阅读
- c++ - 检查两个对象组合的空值的最佳方法
- javascript - 垂直滚动条在 IE8/IE9 中不起作用
- visual-studio-2017 - 切换回 packages.config - 澄清答案
- kubernetes - Kubernetes 上的日志记录和事件跟踪器
- node.js - 如何将 use() 的实例应用于除 app.use(express.static("dist")) 传递的路由之外的所有路由?
- css - 即使在更改版本、硬刷新和清除缓存后 CSS 更改也不会反映
- javascript - 如何在javascript中验证之前修剪非必填字段
- python - 关于用户名和密码加密
- c# - C#动画和音乐同时进行
- php - 使用 DTO 会引发 500 验证异常