Lintcode Fibonacci
Find the Nth number in Fibonacci sequence.
A Fibonacci sequence is defined as follow:
The i th number is the sum of i-1 th number and i-2 th number.
The first ten numbers in Fibonacci sequence is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
Example
Given 1
, return 0
Given 2
, return 1
Given 10
, return 34
Note
The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2
with seed values
F1 = 0 and F2 = 1
Method 1 ( Use recursion )
int fibonacci(int n) { if (n == 1) return 0; else if (n == 2) return 1; return fib(n-1) + fib(n-2); }
Time Complexity: T(n) = T(n-1) + T(n-2) which is exponential. So this is a bad implementation for nth Fibonacci number.
Extra Space: O(n) if we consider the function call stack size, otherwise O(1).
time limited
Method 2 ( Use Dynamic Programming )
int fibonacci(int n) { /* Declare an array to store Fibonacci numbers. */ int f[n+1]; int i; /* 0th and 1st number of the series are 0 and 1*/ f[1] = 0; f[2] = 1; for (i = 2; i <= n; i++) { /* Add the previous 2 numbers in the series and store it */ f[i] = f[i-1] + f[i-2]; } return f[n]; }
Time Complexity: O(n)
Extra Space: O(n)
12~14ms
Method 3 ( Space Otimized Method 2)
We can optimize the space used in method 2 by storing the previous two numbers only because that is all we need to get the next Fibannaci number in series.
int fibonacci(int n) { int a = 0, b = 1, c, i; if( n == 1) return a;
if( n == 2) return b;
for (i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return b; }
10ms
Time Complexity: O(n)
Extra Space: O(1)