Write a function, enter n and find the nth term of the Fibonacci sequence. The definition of the Fibonacci sequence is as follows:
F (0) = 0, F (1) = 1
F (N) = F (N-1) + F (N-2), where N> 1. The
Fibonacci sequence starts from 0 and 1, and then The Fibonacci number is obtained by adding two previous numbers.
The answer needs to be modulo 1e9 + 7 (1000000007). If the initial result of the calculation is: 1000000008, please return 1.
Example 1:
Input: n = 2
Output: 1
Example 2:
Input: n = 5
Output: 5
prompt:
0 <= n <= 100
Source: LeetCode
Link: https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof The
copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
Idea 1: Recursion
Just follow the definition and calculate it later.
class Solution:
def fib(self, n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
a = 0
b = 1
for i in range(2, n+1):
a, b = b, a + b # python交换两个数
return b % 1000000007
Idea 2: Recursion
Adding memory array still times out
class Solution:
def fib(self, n: int) -> int:
self.data = [0] * (n+1)
self.data[1] = 1
return self.f(n)
def f(self, n):
if n == 0:
return 0
elif n == 1:
return 1
if self.data[n] != 0:
return self.data[n]
return (self.f(n-1) + self.f(n-2)) % 1000000007