当前位置:网站首页>剑指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).
边栏推荐
猜你喜欢

Jestson installs IBus input method

Unity基础知识及一些基本API的使用

Hit the wall record (continuously updated)

Thymeleaf quick start learning

Day-7 JVM end

Statistical analysis of catering data --- Teddy cloud course homework

MySQL download and installation environment settings

IP课(OSPF)综合实验

Synergy LAN realizes multi host shared keyboard and mouse (AMD, arm)

IP笔记(11)
随机推荐
How does the latest version of text (TMP) UI text of unity display in Chinese
Demo of UDP communication applied to various environments
IA笔记 1
Dameng database_ Common initialization parameters
简单三步快速实现内网穿透
本地搭建WordPress个人博客,并内网穿透发布上线 (22)
day5-jvm
ue4 换装系统3.最终成果
[principles of database system] Chapter 5 algebra and logic query language: package, extension operator, relational logic, relational algebra and datalog
Dameng database_ Summary of supported data types
Unity(三)三维数学和坐标系统
Jestson installs IBus input method
Dameng database_ Logical backup
不租服务器,自建个人商业网站(4)
ue4 瞄准偏移
Openpose2d transform 3D pose recognition
HoloLens2开发:使用MRTK并且模拟眼动追踪
Unity 3D帧率统计脚本
Dameng database_ Small matters needing attention during use
Write the list to txt and directly remove the comma in the middle