斐波那契数列(动态规划——递推、递归)
利用递推、递归分别实现斐波那契数列(O(n))
/* ------------------------------------------------- Author: wry date: 2022/3/4 15:40 Description: Fibonacci ------------------------------------------------- */ #include <bits/stdc++.h> using namespace std; const int MAXN = 1000+10; int memo[MAXN]; int Fibonacci1(int i) { //O(n) if (memo[i]!=-1) { return memo[i]; } if (i<2) { memo[i] = i; } else { memo[i] = Fibonacci1(i-1) + Fibonacci1(i-2); //递归 } return memo[i]; } int Fibonacci2(int n) { //O(n) for(int i=0;i<=n;i++) { int answer; if (i<2) { answer = n; } else { answer = memo[i-1] + memo[i-2]; //递推 } memo[i] = answer; } return memo[n]; } int main() { memset(memo,-1,sizeof(memo)); int n; while (cin >> n) { cout << Fibonacci1(n); } return 0; }