-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFibbonacci_Number_Leetcode_509.cpp
86 lines (66 loc) · 1.37 KB
/
Fibbonacci_Number_Leetcode_509.cpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int fib(int n) {
if(n <= 1){
return n;
}
return fib(n-1) + fib(n-2);
}
};
class Solution {
public:
//using dp
int solve(int n, vector<int>& dp){
if(n <= 1){
return n;
}
if(dp[n] != -1) return dp[n];
return dp[n] = solve(n-1, dp) + solve(n-2, dp);
}
int fib(int n) {
if(n <= 1){
return n;
}
vector<int> dp(n+1, -1);
return solve(n, dp);
}
};
class Solution {
public:
//using buttom-up approach
int fib(int n) {
if(n<=1) return n;
vector<int> dp(n+1, -1);
dp[0] = 0;
dp[1] = 1;
for(int i = 2; i<=n; i++){
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
};
class Solution {
public:
//using buttom-up approach with constant space complexity
int fib(int n) {
if(n <= 1) return n;
int a = 0;
int b = 1;
int c;
//total number of iteration equal to (n-1)
for(int i = 1; i<n; i++){
c = a+b;
a = b;
b = c;
}
return c;
}
};
int main() {
Solution solution;
int n = 10; // Example input
std::cout << "Fibonacci of " << n << " is " << solution.fib(n) << std::endl;
return 0;
}