当前位置:网站首页>【Yugong Series】July 2022 Go Teaching Course 025-Recursive Function
【Yugong Series】July 2022 Go Teaching Course 025-Recursive Function
2022-07-31 19:27:00 【Huawei cloud】
一、递归函数
如果一个函数在内部调用自身本身,这个函数就是递归函数.
递归函数的优点是定义简单,逻辑清晰.理论上,所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰.
构成递归的条件:
- 子问题须与原始问题为同样的事,且更为简单
- 不能无限制地调用本身,须有个出口,化简为非递归状况处理
1.Basic use of recursive functions
package mainimport "fmt"func main() { c:=Test(3) fmt.Println(c)}func Test(n int) int { // 只有第一排的人才知道自己的排数 if n == 1{ return 1 } // 如果不是第一排,问一下前一排的人 r := Test(n-1) fmt.Println("前一排的排数:",r) // 把前一排人的排数+1,计算出自己的排数. return r+1}
3.相关案例
一个正整数的阶乘(factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1.自然数n的阶乘写作n!.1808年,基斯顿·卡曼引进这个表示法.
亦即n!=1×2×3×…×(n-1)×n.阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n.
package mainvar s int = 1func main() { TestDemo(5) print(s)}func TestDemo(n int) { if n == 1 { return } s *= n TestDemo(n - 1)}
总结
Recursion is when a function can call itself within it,Then this function is a recursive function, that is, a function that calls itself
- 优点:结构清晰,可读性强,可以极大的减少代码量,用有限的语句来定义对象的无限集合.
- 缺点:效率低,调用栈可能会溢出:Every time a function is called, space is allocated on the memory stack,The capacity of each process is limited,当调用的层次太多时,就会超出栈的容量,从而导致溢出.
边栏推荐
- 广汽本田安全体验营:“危险”是最好的老师
- Architect 04 - Application Service Encryption Design and Practice
- Combinatorics Notes (6) Associative Algebra of Locally Finite Partially Ordered Sets, Möbius Inversion Formula
- 1161. 最大层内元素和 : 层序遍历运用题
- Performance optimization: remember a tree search interface optimization idea
- ECCV 2022 华科&ETH提出首个用于伪装实例分割的一阶段Transformer的框架OSFormer!代码已开源!...
- 淘宝/天猫获得淘口令真实url API
- MySQL---多表查询
- multithreaded lock
- 迁移学习——Domain Adaptation
猜你喜欢
【PIMF】OpenHarmony 啃论文俱乐部—盘点开源鸿蒙三方库【3】
iNeuOS工业互联网操作系统,设备运维业务和“低代码”表单开发工具
MySQL---单行函数
Three.js入门
OSPFv3的基本配置
Getting Started with Tkinter
Architect 04 - Application Service Encryption Design and Practice
Three. Introduction to js
What's wrong with the sql syntax in my sql
Jiuqi ny3p series voice chip replaces the domestic solution KT148A, which is more cost-effective and has a length of 420 seconds
随机推荐
杰理语音芯片ic玩具芯片ic的介绍_AD14NAD15N全系列开发
【AcWing】第 62 场周赛 【2022.07.30】
MySQL - single function
移动web开发02
常用的安全渗透测试工具(渗透测试工具)
Taobao/Tmall get Taobao password real url API
Go basic part study notes
基于WPF重复造轮子,写一款数据库文档管理工具(一)
Kotlin coroutines: continuation, continuation interceptor, scheduler
What's wrong with the sql syntax in my sql
返回一个零长度的数组或者空的集合,不要返回null
全平台GPU通用AI视频补帧超分教程
每日练习------随机产生一个1-100之间的整数,看能几次猜中。要求:猜的次数不能超过7次,每次猜完之后都要提示“大了”或者“小了”。
STM32 full series development firmware installation guide under Arduino framework
Three. Introduction to js
Book of the Month (202207): The Definitive Guide to Swift Programming
【NLP】什么是模型的记忆力!
第七章
Teach you how to deploy Nestjs projects
20.支持向量机—数学原理知识