用dp [ i ]存放数列第 i 项,避免了每次递归时都要重复计算海量的项

运行时间从9s提升到0.001s

#include<iostream>
#include<ctime>
using namespace std;
int dp[55];
int f(int x)
{
    if(x==1||x==2) {dp[x]=1;return dp[x];}
    else if(dp[x]!=0) return dp[x];
    else
    {
        dp[x]=f(x-1)+f(x-2);
        return dp[x];
    }
}
int main()
{
    int a;
    cin>>a;
    double st=clock();
    cout<<f(a)<<endl;
    double end=clock();
    cout<<"运行时间为 : "<<(double)((end-st)/CLOCKS_PER_SEC);
    return 0;
}
记忆化搜索