forked from sajdakabir/dp-dynamic-programming-series
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacci_Number.cpp
More file actions
61 lines (53 loc) · 1.07 KB
/
Fibonacci_Number.cpp
File metadata and controls
61 lines (53 loc) · 1.07 KB
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
// memoization
class Solution {
public:
int f(int n,vector<int>&dp){
if(n==0)return 0;
if(n==1)return 1;
if(dp[n]!=-1) return dp[n];
return dp[n]= f(n-1,dp)+f(n-2,dp);
}
int fib(int n) {
vector<int>dp(n+1,-1);
int ans=f(n,dp);
return ans;
}
};
// Time complexity-->O(n) and
// space complexity-->O(n)for axuliry space + O(n) for dp array =O(2n) or O(n)
// Tabulation
class Solution {
public:
int fib(int n) {
if(n==0 || 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];
}
};
// Time complexity-->O(n) and
// space complexity-->O(n) (dp array)
// Space Optimization
class Solution {
public:
int fib(int n) {
if(n==0 || n==1){
return n;
}
int prev2=0;
int prev=1;
for(int i=2;i<=n;i++){
int curr_i=prev2+prev;
prev2=prev;
prev=curr_i;
}
return prev;
}
};
// Time complexity-->O(n) and
// space complexity-->O(1)