当前位置:网站首页>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
}
动态规划
- 用递归的思路分析问题,用循环来解决问题
边栏推荐
- AlibabaProtect. How to delete and uninstall exe
- High-Speed Layout Guidelines 未完...
- channel原创
- vant3+ts DropdownMenu 下拉菜单,数据多能滚动加载
- Two ways of tensorflow2 training data sets
- Codeforces Round #398 (Div. 2) D. Cartons of milk
- Leetcode491 increasing subsequence
- ESP32-C3 ESP-IDF 配置smartconfig 和 sntp 获取网络时间
- C operation database added business data value content case school table
- Are Huishang futures accounts reliable? Is the fund safe?
猜你喜欢

进阶之大山-asp.net core 路由程序基础使用演示0.1

Byte flybook Human Resources Kit three sides

Notes on user experience elements: user centered product design

The server time zone value ‘�й���ʱ��‘ is unrecognized or represents more than one time zone. ......

Arm64棧回溯

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

Unprecedented analysis of Milvus source code architecture

Arm64 Stack backtrack

Continued 2 asp Net core router basic use demonstration 0.2 acquisition of default controller data

Cesium抛物线方程
随机推荐
channel原创
Click the list page of vant3+ts+pinia tab to enter the details. The tab on the details page is highlighted in the original position, and the refresh highlight is in the first item by default
Error record: illegalstateexception: optional int parameter 'XXXX' is
JDBC several pits
联想回应笔记本太多太杂乱:现在是产品调整期 未来将分为数字/Air/ Pro三大系列
Database SQL operation Basics
ESP32-C3 ESP-IDF 配置smartconfig 和 sntp 获取网络时间
Vulnhub[DC3]
低代码平台调研结果
Article name
Arm64 stack backtracking
Project training of Software College of Shandong University - Innovation Training - network attack and defense shooting range experimental platform of Software College of Shandong University (XXV) - p
Are Huishang futures accounts reliable? Is the fund safe?
Second week of electric control learning
Authorization in Golang ProjectUseing Casbin
Nixos 22.05 installation process record
C operation database added business data value content case school table
vant3+ts DropdownMenu 下拉菜单,数据多能滚动加载
Is it cost-effective to apply for Huagui sweet home term life insurance? What are the advantages of this product?
Leetcode491 increasing subsequence