From 8e7d9f579ca973454fdd11f6857f1bd29664db3a Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 1 Jun 2023 15:19:27 -0500 Subject: [PATCH] =?UTF-8?q?Update=200509.=E6=96=90=E6=B3=A2=E9=82=A3?= =?UTF-8?q?=E5=A5=91=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0509.斐波那契数.md | 38 ++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index 195b68ac..cdbf860c 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -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 + + ```