Description of the original title:
Finds the nth number in the Fibonacci sequence.
The so-called Fibonacci sequence refers to:
- The first 2 numbers are 0 and 1.
- The number of I is the number I-1 and the number I-2.
The first 10 digits of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
Topic Analysis:
The beginning of the idea, by recursively implementing output fib (n-1) +fib (n-2) value calculation, the principle is correct, the algorithm is high complexity, resulting in a running time exceeding the Lintcode limit:
Class solution: # @param n:an integer # @return an integer f (n) # recursive implementation def Fibonacci (self, N): If n = = 1: return 0 elif n = = 2: return 1 else: return Self.fibonacci (n-1) + Self.fibonacci (n-2)
Modified to an iterative implementation, the Fibonacci number is saved to the list, loop n-2 times, each time the last element of the sequence [-1] and the penultimate element [-2] is added to the list, and finally return to the last element of the list ~
Class solution: # @param n:an integer # @return an integer f (n) # implement def Fibonacci (self, n) through the For loop iteration: num = [0,1] if n = = 1: return 0 elif n ==1: return 1 for I in Range (0,n-2): num.append (Num[-1] + num[-2]) return Num[-1]
Lintcode Python Entry-level topic Fibonacci sequence