Update 0509.斐波那契数.md

This commit is contained in:
jianghongcheng
2023-06-01 15:19:27 -05:00
committed by GitHub
parent 69361bba97
commit 8e7d9f579c

View File

@ -230,17 +230,41 @@ class Solution:
return dp[n]
```
态规划(版本二)
态规划(版本二)
```python
class Solution:
def fib(self, n: int) -> int:
if n <= 1:
return n
dp = [0, 1]
for i in range(2, n + 1):
total = dp[0] + dp[1]
dp[0] = dp[1]
dp[1] = total
return dp[1]
```
动态规划(版本三)
```python
class Solution:
def fib(self, n: int) -> int:
if n < 2:
if n <= 1:
return n
a, b, c = 0, 1, 0
for i in range(1, n):
c = a + b
a, b = b, c
return c
prev1, prev2 = 0, 1
for _ in range(2, n + 1):
curr = prev1 + prev2
prev1, prev2 = prev2, curr
return prev2
```