mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
dp python
This commit is contained in:
@ -214,6 +214,33 @@ class Solution:
|
||||
a, b = b, c
|
||||
return c
|
||||
|
||||
# 动态规划 (注释版。无修饰)
|
||||
class Solution:
|
||||
def fib(self, n: int) -> int:
|
||||
|
||||
# 排除 Corner Case
|
||||
if n == 1:
|
||||
return 1
|
||||
|
||||
if n == 0:
|
||||
return 0
|
||||
|
||||
# 创建 dp table
|
||||
dp = [0] * (n + 1)
|
||||
|
||||
# 初始化 dp 数组
|
||||
dp[0] = 0
|
||||
dp[1] = 1
|
||||
|
||||
# 遍历顺序: 由前向后。因为后面要用到前面的状态
|
||||
for i in range(2, n + 1):
|
||||
|
||||
# 确定递归公式/状态转移公式
|
||||
dp[i] = dp[i - 1] + dp[i - 2]
|
||||
|
||||
# 返回答案
|
||||
return dp[n]
|
||||
|
||||
# 递归实现
|
||||
class Solution:
|
||||
def fib(self, n: int) -> int:
|
||||
|
Reference in New Issue
Block a user