Fibonacci
ID: 366; naive; 斐波纳契数列
"Solution 1" (Java)
Notes
Classical recursion example
This actually will not pass the test on LintCode (test a relatively large Fibonacci number say the 50th).
Time complexity:
O(2^n)
, extremely bad exponential runtime.Space complexity:
O(1)
, excluding stack space (O(n)
).
Solution 2 (Java)
Notes
This solution uses an array to store the Fibonacci values by the concept of memoization.
Time complexity:
O(n)
Space complexity:
O(n)
Solution 3 (Java)
Notes
This solution also uses the idea of memoization, but it uses a constant number of variables to only store the most important information (current 3 numbers).
n1
,n2
,sum
are the current two numbers and the previous sum of the two numbers.Time complexity:
O(n)
Space complexity:
O(1)
Solution 4 (Java)
Notes
This solution is similar to Solution 2 by using a length-3 array to store the 3 important numbers.
It is also somewhat different because the third element of the array is indeed the current sum of the first and second elements.
Time complexity:
O(n)
Space complexity:
O(1)
Solution 5 (Java)
Notes
By the above mathematical rule of Fibonacci numbers, we have this solution.
Note that the loop does not run for
n = 1, 2, 3
nor any non-positive numbers. So it starts withn = 4
in the code, but n is actually 2 in the formula and the top-left element would be F3, which is the correct result for the inputn = 4
in the code.Time complexity:
O(n)
Space complexity:
O(1)
Solution 6 (Java)
Notes
Using the same idea in Solution 5, we optimize the
power
function by usingdivide and conquer
. This idea is also illustrated in this Pow(x, n) problem.Time complexity:
O(log n)
Space complexity:
O(1)
This solution can also be extended by deriving a recursive relation from the matrix multiplication. The formula/relation is:
When n is even and k = n / 2,
When n is even and k = (n+1) / 2,
The derivation is shown here:
This extension would have the same time and space complexity as done in code above. The reason is that this is still essentially divide and conquer where
k
is half ofn
each time.
Solution 7 (Java)
Notes
This solution uses the mathematical formula for calculation (not the recursive relation).
Note that
n--
because the problem is 1-indexed.Time complexity:
O(log n)
with the assumption thatMath.pow
takeslog n
time.Space complexity:
O(1)
.
Last updated