diff --git "a/problems/0509.\346\226\220\346\263\242\351\202\243\345\245\221\346\225\260.md" "b/problems/0509.\346\226\220\346\263\242\351\202\243\345\245\221\346\225\260.md" index 195b68acec..cdbf860cba 100644 --- "a/problems/0509.\346\226\220\346\263\242\351\202\243\345\245\221\346\225\260.md" +++ "b/problems/0509.\346\226\220\346\263\242\351\202\243\345\245\221\346\225\260.md" @@ -230,17 +230,41 @@ class Solution: return dp[n] ``` -动态规划(版本二) +态规划(版本二) ```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 + + 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 <= 1: + return n + + prev1, prev2 = 0, 1 + + for _ in range(2, n + 1): + curr = prev1 + prev2 + prev1, prev2 = prev2, curr + + return prev2 + + ```