当前位置:网站首页>My recursive never burst stack
My recursive never burst stack
2022-08-02 20:35:00 【Senior Fishing Engineer】
When talking about algorithms,「递归」There is no way a skill,Because many algorithms actually use this technique to achieve.
那么问题来了,bad use of recursion「爆栈」️️️ StackOverFlow
but ! 「尾递归」不会爆栈!
So what are the characteristics of tail recursion compared to normal recursion??
- tail calling the function itself,No redundant calculation logic.
- Optimize stack space,从O(n)到O(1)
以 Python 为例,Mainly distinguish the use of stack space between ordinary recursion and tail recursion:
def recsum(x):
if x == 1:
return x
else:
return x + recsum(x - 1)
调用recsum(5)为例,The corresponding stack space changes are as follows:
recsum(5)
5 + recsum(4)
5 + (4 + recsum(3))
5 + (4 + (3 + recsum(2)))
5 + (4 + (3 + (2 + recsum(1))))
5 + (4 + (3 + (2 + 1)))
5 + (4 + (3 + 3))
5 + (4 + 6)
5 + 10
15
可观察,stack left to right,Increase to a peak and then calculate from right to left,This is often we don't want to.修改以上代码,can be tail recursive:
def tailrecsum(x, running_total=0):
if x == 0:
return running_total
else:
return tailrecsum(x - 1, running_total + x)
Compare the memory consumption of the latter tail recursion:
tailrecsum(5, 0)
tailrecsum(4, 5)
tailrecsum(3, 9)
tailrecsum(2, 12)
tailrecsum(1, 14)
tailrecsum(0, 15)
15
ps : tailrecsum(4, 5) 执行的时候,tailrecsum(5, 0) It can actually be recycled on the stack..
You can see that tail recursion is compared to normal recursion,stack space does itO(1)的复杂度,It also plays a role in memory optimization..
then because it isO(1)复杂度,It's definitely not going to explode.
引用
边栏推荐
猜你喜欢
随机推荐
二叉查找树的查找
Mysql和Redis如何保证数据一致性
Gear 月度更新|6 月
Redis总结_实战篇
详细教学——1688关键词搜索API操作流程
故障分析 | 一条 SELECT 语句跑崩了 MySQL ,怎么回事?
恒驰5真的没大卖
基于HDF的LED驱动程序开发(1)
golang源码分析(4):select
Wechat Gymnasium Appointment Mini Program Graduation Design Finished Works (7) Mid-term Inspection Report
54.【system系统互动函数大总结】
打补丁的日子,比写代码的日子难熬多了
C# 术语
再获权威认证!马上消费安逸花APP通过中国信通院“金融APP人脸识别安全能力评测”
HDF驱动框架的API(2)
影响PoE供电传输距离的除了网线还有啥?
Flink学习9:配置idea开发flink-Scala程序环境
golang刷leetcode 经典(6) 实现跳表
Several common cross-domain solutions
白话电子签章原理及风险