当前位置:网站首页>剑指offer JZ10斐波那契数列
剑指offer JZ10斐波那契数列
2022-07-24 05:22:00 【喜乐自在】

很多同学在刚开始学习递归时,斐波那契数列是一个经典的例子,在解决此题中,递归的思想同时扮演着重要的角色。
解法1:
class Solution {
public:
int Fibonacci(int n) {
if(n<=2)
return 1; //先解决n=1或2的特殊情况
else
return Fibonacci(n-1)+Fibonacci(n-2); //调用函数,例如 求f(3)时,f(3)=f(2)+f(1);
// 同理f(4)=f(3)+f(2);层层向内调用,直到求出值
}
};这种解法的优点是思路清晰,代码简单,但是递归的调用,导致空间复杂度过于的即 递归中生成栈的空间。且存在很多次的重复计算:

为了减少重复计算造成的不必要空间开支,我们可以采用c++中的map容器来存储已经计算过的
f(n)
class Solution {
public:
map<int,int> map_flag;//记录已经被计算出来的值
int Fibonacci(int n) {
if(n<=1) return n;//f(0)=0,f(1)=1,初始状态
if(map_flag.count(n)){//已经被计算过;采用count的函数可以降低内存与时间;
return map_flag[n];//第n项的值
}
return map_flag[n]=Fibonacci(n-1)+Fibonacci(n-2);//未被计算过,存入map;
}
};为了进一步减少空间和时间复杂度。我们尝试使用递归改迭代的方式
class Solution {
public:
int Fibonacci(int n) {
if(n<=1)return n;//特别判断斐波拉契数列前两项值 f(0)=0; f(1)=1
int l1=0,l2=1;//用来保留前两项的值
for (int i=2; i<=n; ++i) {
int temp=l1+l2; //第一次temp值为前后两项的和
l1=l2; // l1记录当前项
l2=temp; //l2记录不包扩当前项的累和
}
return l2; //返回总和
}
};
空间复杂度为常数阶o(1),时间复杂度为o(n).
边栏推荐
- Hololens 2 Chinese development document MRTK V2
- Dameng database_ Logical backup
- Dameng database_ Various methods of connecting databases and executing SQL and scripts under disql
- QT char to qstring hexadecimal and char to hexadecimal integer
- QT drawing exception using pure code
- Unity2d game let characters move - next
- Accurate calculation of time delay detailed explanation of VxWorks timestamp
- 不租服务器,自建个人商业网站(2)
- IP笔记(8)
- Unicast, multicast, broadcast, tool development, introduction to QT UDP communication protocol development and source code of development tools
猜你喜欢
随机推荐
Lunix命令入门 - 用户及文件权限(chmod 详解)
Openpose2d转换3d姿态识别
Openpose Unity 插件部署教程
论文阅读-Endmember-Guided Unmixing Network (EGU-Net) 端元指导型高光谱解混网络
Unity(三)三维数学和坐标系统
如何建立一个仪式感点满的网站,并发布到公网 2-2
day5-jvm
JDBC advanced -- learning from Shang Silicon Valley (DAO)
Data warehouse and data warehouse modeling
unity2D游戏之让人物动起来-下
Unity 3D frame rate statistics script
异地远程连接在家里的群晖NAS【无公网IP,免费内网穿透】
Hololens 2 development: use MRTK and simulate gesture input in unity
Day2 websocket+ sort
通道注意力与空间注意力模块
Opencv reads avi video and reports an error: number < Max_ number in function ‘icvExtractPattern
Using keras to realize multidimensional (multivariable) time series prediction of cnn+bilstm+attention
Dameng database_ LENGTH_ IN_ Influence of char and charset
JDBC进阶—— 师承尚硅谷(DAO)
Write the list to txt and directly remove the comma in the middle









