-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacci_DP.cpp
More file actions
executable file
·62 lines (48 loc) · 1007 Bytes
/
Fibonacci_DP.cpp
File metadata and controls
executable file
·62 lines (48 loc) · 1007 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Fiboncci Series using Dynamic Programming
#include <iostream>
using namespace std;
// Top Down Approach
int fib_TD(int n, int dp[]){
if(n == 0 || n==1){
return n;
}
if(dp[n] != 0){
return dp[n];
}
int ans;
ans = fib_TD(n - 1, dp) + fib_TD(n - 2, dp);
return dp[n] = ans;
}
// Bottom Up Approach
int fib_BU(int n){
int dp[1000] = {0};
dp[1] = 1;
for(int i = 2; i <= n; i++){
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
// Bottom Up Space Optimised
int fib_SpaceOpt(int n){
if(n == 0 || n==1){
return n;
}
int a = 0;
int b = 1;
int c;
for(int i = 2; i <= n; i++){
c = a + b;
a = b;
b = c;
}
return c;
}
int main(){
int n;
cin >> n;
int dp[1000] = {0};
cout << fib_BU(n) << endl;
cout << fib_TD(n, dp) << endl;
cout << fib_SpaceOpt(n) << endl;
return 0;
}