过去会遗忘,现在不会

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
斐波那契数列

动态规划入门,复习一下。

正序计算。

复制代码
class Solution {
public:
    int fib(int n) {
unordered_map<int,int> map;
map.emplace(0,0);
map.emplace(1,1);
map.emplace(2,1);
if (n<3) return map.find(n)->second;
for(int i=3;i<=n;i++)
{
    int a=map.find(i-1)->second;
    int b=map.find(i-2)->second;
    map.emplace(i,a+b);
}
return map.find(n)->second;
    }
};
复制代码

优化一下正序计算过程,每次只要存当前位置的前两个数的值即可。

复制代码
class Solution {
public:
    int fib(int n) {
int a=0;
int b=1;
if(n==0) return a;
if(n==1) return b;
for(int i=2;i<=n;i++)
{
int temp=a;
a=b;
b=temp+b;
}
return b;
    }
};
复制代码

当然直接通项公式也不是不行。

经典递归(逆序)

复制代码
class Solution {
public:
    int fib(int n) {
if(n==0) return 0;
if(n==1) return 1;
if(n>1) return fib(n-1)+fib(n-2);

return 0;
    }
};
复制代码

逆序递归可以优化避免重复计算

复制代码
class Solution {
public:
    int nums[31]={0,1};
    
    int fib(int n) 
    {
    //nums[1]=1;
    if(n<2) return nums[n];
    if(nums[n]>0) return nums[n];
    nums[n]=fib(n-1)+fib(n-2);
   
    return nums[n];
    }
};
复制代码

一开始把定义数组的语句写在函数内了,我说怎么比递归还慢。

 

posted on   WhatAnyWay  阅读(12)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示