homi @ 2023-03-08 21:11:07
#include<bits/stdc++.h>
using namespace std;
int n,len=1;
int f[5010][5010];
int work(int k)
{
if(k==1)return 1;
if(k==2)return 2;
f[k][1]=work(k-1)+work(k-2);
return f[k][1];
}
int main()
{
cin>>n;
f[1][1]=1;
f[2][1]=2;
for(int i=3;i<=n;i++)
work(i);
for(int k=1;k<=n;k++)
for(int i=1;i<=len;i++)
{
if(f[k][i]>=10)
{
f[k][i+1]+=f[k][i]/10;
f[k][i]%=10;
if(f[k][len+1]>0)len++;
}
}
for(int i=len;i>=1;i--)
cout<<f[n][i];
return 0;
}
by homi @ 2023-03-09 10:39:14
为啥用递归就超时呢 ,高精度加法反而可以过
by Miss_SGT @ 2023-03-18 00:34:31
直接递归时间复杂度特别高,应该只能做到n=10左右,你要么用递推,要么写记忆化
by homi @ 2023-03-19 07:08:22
@zhouchenqiao1 好的 谢谢
by Roger_Spencer @ 2023-03-20 09:25:08
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define endl "\n"
const int N = 1e5 + 10;
const int M = 5510;
int dp[N];
vector<int> add(vector<int> &A, vector<int> &B)
{
if (A.size() < B.size()) return add(B, A);
vector<int> C;
int t = 0;
for (int i = 0; i < A.size(); i ++ )
{
t += A[i];
if (i < B.size()) t += B[i];
C.push_back(t % 10);
t /= 10;
}
if (t) C.push_back(t);
return C;
}
void solve()
{
int n;
cin >> n;
if ( n == 1)
{
cout << 1 << endl;
return;
}
vector<int> A, B, C, D;
A.push_back(1);
B.push_back(1);
for (int i = 2; i <= n; i ++ )
{
C = add(A, B);
A = B;
B = C;
}
for (int i = C.size() - 1; i >= 0; i -- ) cout << C[i];
cout << endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
solve();
return 0;
}
by wcy110614 @ 2023-05-21 11:19:12
普通递归的时间复杂度相当高,会计算很多重复的部分。
所以说你就要优化算法,要么用记忆化,要么就写普通的方法