当前位置:网站首页>递归优化之缓存结果(js)
递归优化之缓存结果(js)
2022-07-16 13:46:00 【一枚小银子】
为啥要优化?
有时候递归里会有大量重复运算,肯定没必要啊,这时候缓存是个好东西。
举个代表性例子:
斐波拉契数列,由0和1开始,后面每项数值为前两数之和,
0 1 1 2 3 5 8 ......
不做优化的递归:
const fn = n => {
if (n < 2) return n
return fn(n - 1) + fn(n - 2)
}若计算第100项,左边fn(99) + 右边fn(98),左右两边是不是都要共同计算fn(97)、fn(96)、fn(95)、fn(94)、......,现在,缓存它!!!
优化后的递归:
const fn = (n) => {
const cache = {};
const dfs = (n) => {
if (n < 2) return n;
if (cache[n]) return cache[n];
cache[n] = dfs(n - 1) + dfs(n - 2);
return cache[n];
};
};当n越大,加上缓存的递归效率就越明显了
边栏推荐
- S7-200SMART案例分析——运动控制编程(二)
- QT4: develop "work diary" from scratch (1) -worklog project
- JD finance, are you bad, or are you cutting too much??
- Concept correlation and pattern matching of strings
- 【Leetcode】225. 用队列实现栈
- Xray安装使用
- 网络爬虫爬取三国演义所有章节的标题和内容(BeautifulSoup解析)
- 栈的基本操作
- Thread.sleep简介说明
- 2022 G3 boiler water treatment examination question bank and simulation examination
猜你喜欢
![[dynamic programming]dp20 calculation string editing distance - medium](/img/89/9c56bc84e07f0c253a66b837f14232.png)
[dynamic programming]dp20 calculation string editing distance - medium

【产品人卫朋】2022年产品人必备的13个设计类网站(1.0版)

MySQL超详细安装教程 手把手教你安装MySQL到使用MySQL 最简单的MySQL安装方式,这种方式装,卸载也简单

T-无限的路

ASP.NET印刷行业印务管理系统,源码免费分享

L'art de l'annotation de code, un bon Code n'a - t - il vraiment pas besoin d'annotation?

Resolved SQL_ ERROR_ INFO: “You have an error in your SQL syntax; check the manual that corresponds to your

The simple solution the boss wants vs. the needs the programmer understands | cartoon

监督学习week 3: Logistic Regression optional_lab收获记录

HALCON联合C#检测表面缺陷——ROI交互(三)(和图片同步缩放裁剪等功能)
随机推荐
请查收,您有一份阿里先锋开源项目清单
【C语言进阶】⑨动态内存分配知识总结 超详细
网络爬虫爬取b站励志弹幕并生成词云(精心笔记总结)
L'art de l'annotation de code, un bon Code n'a - t - il vraiment pas besoin d'annotation?
基于亚马逊云科技无服务器服务快速搭建电商平台——部署篇
Thread. Introduction to sleep
100% accuracy, Alibaba business travel billing system architecture design practice
Xray installation and use
【开发教程7】疯壳·开源蓝牙智能健康手表-充电
串的概念相关及模式匹配
20220715 国内Conda不fq安装Pytorch最新版本的方法
Enter a URL and explain the whole process
走不下去恶补基础呢--C#线程开发输出字符串程序
(pytorch进阶之路五)RNN/LSTM/LSTMP/GRU
NoSQLAttack工具下载与使用
Instance Noise A trick for stabilising GAN training
Nature Microbiology | 枯草芽孢杆菌生物膜促进甜瓜生长并抗病
pycuda 安装完毕,验证步骤
数据可视化之matplotlib绘制正余弦曲线图
程序分析与优化 - 11 多分支分析