当前位置:网站首页>【愚公系列】2022年07月 Go教学课程 025-递归函数
【愚公系列】2022年07月 Go教学课程 025-递归函数
2022-08-01 03:37:00 【愚公搬代码】
一、递归函数
如果一个函数在内部调用自身本身,这个函数就是递归函数。
递归函数的优点是定义简单,逻辑清晰。理论上,所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰。
构成递归的条件:
- 子问题须与原始问题为同样的事,且更为简单
- 不能无限制地调用本身,须有个出口,化简为非递归状况处理
1.递归函数的基本使用
package main
import "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 main
var s int = 1
func main() {
TestDemo(5)
print(s)
}
func TestDemo(n int) {
if n == 1 {
return
}
s *= n
TestDemo(n - 1)
}
总结
递归就是一个函数在其内部可以调用其本身,那么这个函数就是递归函数即自己调用自己的函数
- 优点:结构清晰,可读性强,可以极大的减少代码量,用有限的语句来定义对象的无限集合。
- 缺点:效率低,调用栈可能会溢出:函数每次调用都会在内存栈中分配空间,而每个进程的容量是有限的,当调用的层次太多时,就会超出栈的容量,从而导致溢出。
边栏推荐
- Simple and easy to use task queue - beanstalkd
- Dart 命名参数语法
- IDEA debugging
- leetcode6133. 分组的最大数量(中等)
- The 16th day of the special assault version of the sword offer
- Flutter “Hello world“ 程代码
- This article takes you to understand the past and present of Mimir, Grafana's latest open source project
- 【SemiDrive源码分析】系列文章链接汇总(全)
- Ordinary users cannot access HGFS directory
- The maximum quantity leetcode6133. Grouping (medium)
猜你喜欢
ARM cross compilation
Completely closed Chrome updated and in the top right corner of the tip
MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data
The maximum quantity leetcode6133. Grouping (medium)
简单易用的任务队列-beanstalkd
The 16th day of the special assault version of the sword offer
[cellular automata] based on matlab interface aggregation cellular automata simulation [including Matlab source code 2004]
被 CSDN,伤透了心
By CSDN, torn
【分层强化学习】HIRO:Data-Efficient Hierarchical Reinforcement Learning
随机推荐
Replacing the Raspberry Pi Kernel
Device tree - conversion from dtb format to struct device node structure
IDEA does not recognize the module (there is no blue square in the lower right corner of the module)
button去除黑框
【Make YOLO Great Again】YOLOv1-v7全系列大解析(Neck篇)
lambda
What is dynamic programming and what is the knapsack problem
带wiringPi库在unbutu 编译 并且在树莓派运行
智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”
785. Quick Sort
How to write a high-quality digital good article recommendation
"ArchSummit: The cry of the times, technical people can hear"
预言机简介
二舅
The fledgling Xiao Li's 113th blog project notes: Wisdom cloud smart flower watering device combat (2) - basic Demo implementation
Error using ts-node
最新 955 不加班的公司名单
Take you to experience a type programming practice
软件测试面试(三)
The fledgling Xiao Li's 114th blog project notes: Wisdom cloud intelligent flower watering device combat (3) - basic Demo implementation