TheAlgorithms-C-Plus-Plus/dynamic_programming/Fibonacci_Top_Down.cpp

26 lines
396 B
C++
Raw Normal View History

2016-11-25 21:06:34 +08:00
#include <bits/stdc++.h>
using namespace std;
int arr[1000000];
2019-08-21 10:10:08 +08:00
int fib(int n)
{
if (arr[n] == -1)
{
if (n <= 1)
2016-11-25 21:06:34 +08:00
arr[n] = n;
else
2019-08-21 10:10:08 +08:00
arr[n] = fib(n - 1) + fib(n - 2);
2016-11-25 21:06:34 +08:00
}
return arr[n];
}
int main(int argc, char const *argv[])
{
int n;
2019-08-21 10:10:08 +08:00
cout << "Enter n: ";
cin >> n;
for (int i = 0; i < n + 1; ++i)
2016-11-25 21:06:34 +08:00
{
arr[i] = -1;
}
2019-08-21 10:10:08 +08:00
cout << "Fibonacci number is " << fib(n) << endl;
2016-11-25 21:06:34 +08:00
return 0;
}