Title Description
We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0). n <= 39
1. recursion
-
Analysis
Fibonacci standard formula of Number is: F (1) = 1, F (2) = 1, F (n) = F (n-1) + (n> = 3 F (n-2), n ∈N *)
according to the formula directly write: -
Code
-
Complexity
Time Complexity:
spatial complexity:
2. Optimize recursive
-
Analysis of
recursive calculation is repeated a lot of the same data, we use an array to store the result up 8! -
Code
-
Complexity
time complexity: O (n) O (n )
space complexity: O (n) O (n )
3. Optimizing Storage
- Analysis of
fact, we can find a time to use the two most recent numbers, so we can store only the last two numbers
- sum of n items stored value
- one stored value of the n-1 items
- the stored value of the two items n-2
- Code
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
preNum = 1
prePreNum = 0
result = 0
if n == 0:
return 0
if n == 1:
return 1
# [0,1,1,2]
for i in range(2,n+1):
result = preNum + prePreNum
prePreNum = preNum
preNum = result
return result
- Complexity:
time complexity: O (n) O (n )
complexity of space: O (1) O (1 )