Article Directory
1. Problem description
Fibonacci number, usually expressed by F(n), the sequence formed is called Fibonacci sequence. The number sequence starts with 0 and 1, and each number after it is the sum of the previous two numbers. That is:
F(0) = 0, F(1) = 1
F(n) = F(n-1) + F(n-2), where n> 1
Give you n, please calculate F(n).
Example 1:
Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1
Example 2:
Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2
Example 3:
Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3
prompt:
0 <= n <= 30
Source: LeetCode
Link: https://leetcode-cn.com/problems/fibonacci-number
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
2. Thinking analysis and code
1. Recursion
Using F(n) = F(n-1) + F(n-2), the most direct
def fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fib(n-1)+fib(n-2)
print(fib(10))
2. Recursion
n here refers to the n in f(n), n starts from 0, when n is less than or equal to 1, it is returned to itself, and the loop analog sequence is added
def fib2(n):
a,b = 0,1
if n <= 2:
return n
for i in range(n-2):
c=a+b
print(c)
a,b = b,c
return c
3. Other methods (see the solution to learn)
1. Recursion, dynamic programming
The idea of this question is similar to my second one, except that a list is used to store the data
class Solution:
def fib(self, n: int) -> int:
data = [0, 1]
for i in range(n-1):
data.append(data[-2] + data[-1])
return data[n]
2. Recursion, dynamic programming, and optimized storage
are also similar to my second type, except that an intermediate variable c is omitted
class Solution:
def fib(self, n: int) -> int:
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
There are also some unpopular methods, which in the final analysis are links to math
problem solutions