当前位置:网站首页>【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,当调用的层次太多时,就会超出栈的容量,从而导致溢出.
边栏推荐
- Shell 脚本 快速入门到实战 -02
- Get Douyin Video Details API
- The article you worked so hard to write may not be your original
- Bika LIMS 开源LIMS集—— SENAITE的使用(检测流程)
- 保证接口数据安全的10种方式
- BOW/DOM(上)
- Kotlin coroutines: continuation, continuation interceptor, scheduler
- Poker Game in C# -- Introduction and Code Implementation of Blackjack Rules
- MySQL---aggregate function
- 财务盈利、偿债能力指标
猜你喜欢
随机推荐
ojdbc8 "Recommended Collection"Mobile web development 02
MySQL---operator
Kotlin协程:续体、续体拦截器、调度器
Basic configuration of OSPFv3
<artifactId>ojdbc8</artifactId>「建议收藏」
深度学习中的batch(batch size,full batch,mini batch, online learning)、iterations与epoch
Bika LIMS 开源LIMS集—— SENAITE的使用(检测流程)
Chinese encoding Settings and action methods return values
Taobao/Tmall get Taobao password real url API
Basics of ResNet: Principles of Residual Blocks
【AcWing】The 62nd Weekly Match 【2022.07.30】
-xms -xmx(information value)
性能优化:记一次树的搜索接口优化思路
iNeuOS工业互联网操作系统,设备运维业务和“低代码”表单开发工具
[PIMF] OpenHarmony Thesis Club - Inventory of the open source Hongmeng tripartite library [3]
Combinatorics Notes (6) Associative Algebra of Locally Finite Partially Ordered Sets, Möbius Inversion Formula
leetcode:6135. 图中的最长环【内向基环树 + 最长环板子 + 时间戳】
PCB stackup design
Three.js入门