惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
酷 壳 – CoolShell
酷 壳 – CoolShell
美团技术团队
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
罗磊的独立博客
S
SegmentFault 最新的问题
D
Docker
博客园 - 司徒正美
雷峰网
雷峰网
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
G
Google Developers Blog
The GitHub Blog
The GitHub Blog
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - Franky
月光博客
月光博客
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
MyScale Blog
MyScale Blog
MongoDB | Blog
MongoDB | Blog

博客园 - Eagle6970

ASP.NET Core实现MCP Streamable HTTP 豆包生成C#微博API HTTP调用实例代码 豆包生成C#即梦API HTTP调用实例代码 SQL Server - sp_spaceused 子网掩码和IP地址范围 [VS Code] Run JavaScript [VS Code] Copy所有包含关键字的行 [数据结构学习笔记25] 归并排序(Merge Sort) [VS Code] 使用dotnet CLI安装和管理NuGet包 [数据结构学习笔记24] 选择排序(Selection Sort) [数据结构学习笔记23] 插入排序(Insertion Sort) [数据结构学习笔记22] 冒泡排序(Bubblesort) [数据结构学习笔记21] 快速排序(Quicksort) [数据结构学习笔记20] 深度优先搜索(DFS)和广度优先搜索(BFS) [数据结构学习笔记19] 二叉树遍历(Binary Tree Traversal) [数据结构学习笔记18] 二分查找(Binary Search) [数据结构学习笔记17] 线性查找(Linear Search) [数据结构学习笔记16] 汉诺塔(Towers of Hanoi) [数据结构学习笔记15] 斐波那契数列(Fibonacci)
[数据结构学习笔记14] 递归简介(Recursion)
Eagle6970 · 2025-01-15 · via 博客园 - Eagle6970

递归让我们把问题由大分小,小到我们能够轻松处理。递归方法有两个要注意的点:1. 递归方法会重复的被调用;2. 必须有一个终止条件,否则方法调用不停,会导致stack overflow。

看下面的一个例子,这个没有终止条件,会报错!

function hello() {
  console.log("I'm a little function, short and stout!");  
  hello();
} // Uncaught RangeError: Maximum call stack size exceeded

注意这里hello()里面调用了hello(),这就是递归,自己调用自己,但是这里它没有终止条件,所以会无限调用,会报错误!

 添加终止条件

function hello(num) {
   if (num <= 1) {
      return num; // termimating condition
   } else {
       // recursive function call
       return num + hello(num - 1);
   }
} 

我们来调用一下这个方法,比如hello(3):

hello(3) -> return 3 + hello(2) -> return 3 + 2 + hello(1) 

                                                                               ↓

  return 6;    ←        return 3 + 3;    ←         return 3 + 2 + 1;

再强调一下递归要注意的两点:

1. 自己调用自己

2. 要有终止条件