当前位置:网站首页>js求斐波那契数列
js求斐波那契数列
2022-06-12 17:58:00 【走出自闭的鸟儿】
斐波那契数列
第一个数为0,第二个数为1,之后每个数都是前两个数之和
// 递归O(2^n)
function fibonacci(n){
if(n<=0) return 0
if(n===1) return 1
return fibonacci(n-1) + fibonacci(n-2)
}

优化
- 不用递归、用循环
- 记录中间结果
- 时间复杂度为O(n)
// O(n)
function fibonacci(n){
if(n<=0) return 0
if(n===1) return 1
let n1 = 1 // 记录n-1的结果
let n2 = 0 // 记录n-2的结果
let res = 0
for(let i =2 ;i<=n;i++){
res = n1+n2
// 记录中间结果
n2 = n1
n1 = res
}
return res
}
动态规划
- 用递归的思路分析问题,用循环来解决问题
边栏推荐
- 小程序和App同时拥有?两者兼得的一种技术方案
- Small program +app, a low-cost and active technology combination idea
- Use applet to quickly generate app in seven steps
- C#简单介绍
- Original error interface
- Arm64 stack backtracking
- Vant3 +ts packaged simple step advancer component
- 消息队列存储消息数据的 MySQL 表格
- A method of quickly reusing wechat login authorization in app
- 数组按指定顺序排序
猜你喜欢

App中快速复用微信登录授权的一种方法

vant3 +ts 封装简易step进步器组件

消息队列存储消息数据的 MySQL 表格

Unprecedented analysis of Milvus source code architecture

Vant3+ts dropdownmenu drop-down menu, multi data can be scrolled

消息队列实战之队列优先级

Byte flybook Human Resources Kit three sides

A method of quickly reusing wechat login authorization in app

字节飞书人力资源套件三面

vant3+ts h5页面嵌套进app 与原生app通信
随机推荐
Goframe gredis configuration management | comparison of configuration files and configuration methods
Unprecedented analysis of Milvus source code architecture
Variable of C #
Arm64棧回溯
Research results of low code platform
重构--梳理并分解继承体系
Schematic diagram of active differential crystal oscillator and differences among lv-pecl, LVDS and HCSL
Stream流注意点
机器学习系列(5):朴素贝叶斯
Leetcode 718 longest common substring
MIPS general purpose register + instruction
leetcode 647. 回文子串
消息队列实战之队列优先级
[csp]202012-2 optimal threshold for period end forecast
vant3 +ts 封装简易step进步器组件
Tensorflow prompts typeerror: unsupported operand type (s) for *: 'float' and 'nonetype‘
Extreme Programming -- Practice of root cause analysis
认识函数原创
Vulnhub[DC3]
Error record: illegalstateexception: optional int parameter 'XXXX' is