-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFibonacciNumber_509.cpp
61 lines (46 loc) · 982 Bytes
/
FibonacciNumber_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
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 509. Fibonacci Number
~ Link : https://leetcode.com/problems/fibonacci-number/
*/
// Recursive Approach
/*
class Solution {
public:
int fib(int n) {
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
};
*/
// TOP-DOWN Approach (Memoization)
/*
class Solution {
public:
int dp[31];
int fibo(int n) {
if (n <= 1)
return n;
if (dp[n] != -1)
return dp[n];
return dp[n] = fibo(n - 1) + fibo(n - 2);
}
int fib(int n) {
memset(dp, -1, sizeof(dp));
return fibo(n);
}
};
*/
// BOTTOM-UP Approach (Tabulation)
class Solution {
public:
int dp[31];
int fib(int n) {
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; ++i)
dp[i] = dp[i - 1] + dp[i - 2];
return dp[n];
}
};