1. This is a general recursion (exponential explosion type, time complexity O (1.618 ^ n )):
#include <iostream>#include <cstdio>using namespace std;__int64 Fib(int n){if(n == 1 || n == 2)return 1;return Fib(n - 1) + Fib(n - 2);}int main(void){int n;while(cin >> n)printf("%I64d\n", Fib(n));return 0;}
2. After reading the introduction to dynamic planning today, I think that the method for creating a memo table is quite good, and it is also in line with people's thinking (this is very important), so I am like, I wrote a recursive Fibonacci number with a memo table. This should be a space for time. The memo table is global. Once it is built, it will be easy to do later.
#include <iostream>#include <cstdio>using namespace std;__int64 aFib[90] = {0};//aFib[] correspond to Fib(), and global!__int64 Fib(int n){if(n == 1 || n == 2)return 1;if(aFib[n - 1] == 0)//Fib(n-1) have been not calculatedaFib[n - 1] = Fib(n - 1);if(aFib[n - 2] == 0)//Fib(n-2) have been not calculatedaFib[n - 2] = Fib(n - 2);return aFib[n - 1] + aFib[n - 2];}int main(void){int n;while(cin >> n)printf("%I64d\n", Fib(n));return 0;}
This is my first application to learn dynamic planning! Although it does not fully reflect the charm of Dynamic Planning (optimal solution. Continue learning...
Update
This method is called search + Dynamic Planning, which simplifies the second program by the way:
#include <iostream>#include <cstdio>using namespace std;__int64 aFib[90] = {0, 1, 1};//aFib[] correspond to Fib(), and global!unsigned __int64 Fib(const unsigned int n){if(aFib[n] == 0)//Fib(n) have been not calculatedaFib[n] = Fib(n - 1) + Fib(n - 2);return aFib[n];}int main(void){int n;while(cin >> n)printf("%I64d\n", Fib(n));return 0;}
Update
General formula, the time-space complexity is O (1)
#include <iostream>#include <cstdio>using namespace std;int main(void){int n;while(cin >> n)printf("%.0f\n", 0.4472135955 * pow(1.618033988745, n) );return 0;}