Skip to content

Commit 1532d69

Browse files
Create Fibonacci number.cpp
1 parent 7eb090d commit 1532d69

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

LeetCode/Fibonacci number.cpp

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
Solution 1 - Recursive Approach
2+
Time Complexity - O(2^N)
3+
Space Complexity - O(N) given the function call stack size
4+
5+
int fib(int N) {
6+
if(N == 0) return 0;
7+
if(N == 1) return 1;
8+
return fib(N-1) + fib(N-2);
9+
}
10+
11+
12+
Solution 2 - Dynamic Programming Approach
13+
Use memoization to store perviously computed fibonacci values.
14+
Time Complexity - O(N)
15+
Space Complexity - O(N)
16+
17+
int fib(int N) {
18+
if(N < 2)
19+
return N;
20+
int memo[N+1];
21+
memo[0] = 0;
22+
memo[1] = 1;
23+
for(int i=2; i<=N; i++)
24+
memo[i] = memo[i-1] + memo[i-2];
25+
return memo[N];
26+
}
27+
28+
29+
Solution 3 - Imperative Approach (Bottom Up DP)
30+
With Imperative approach, we step through the loop and optimize the space by storing only two previous fibonacci values in two variables.
31+
Time Complexity - O(N)
32+
Space Complexity - O(1)
33+
34+
int fib(int N) {
35+
if(N < 2)
36+
return N;
37+
int a = 0, b = 1, c = 0;
38+
for(int i = 1; i < N; i++)
39+
{
40+
c = a + b;
41+
a = b;
42+
b = c;
43+
}
44+
return c;
45+
}
46+
47+
48+
Solution 4 - Binet's Nth-term Formula
49+
Using Binet's Formula for the Nth Fibonacci involves the usage of our golden section number Phi.
50+
Phi = ( sqrt(5) + 1 ) / 2
51+
Using approximation equation is good enough here, since we know N >= 0 && N <= 30, we can safely use the following rounded function
52+
Fib(N) = round( ( Phi^N ) / sqrt(5) )
53+
Full mathematical explanation of Binet's Formula here
54+
Time Complexity - O(1)
55+
Space Complexity - O(1)
56+
57+
int fib(int N) {
58+
double phi = (sqrt(5) + 1) / 2;
59+
return round(pow(phi, N) / sqrt(5));
60+
}

0 commit comments

Comments
 (0)