基本概念:
Dynamic Programming,简称DP,如果某一问题有很多重叠子问题,使用动态规划是最有效的。
所以动态规划中每一个状态一定是由上一个状态推导出来的,这一点就区分于贪心,贪心没有状态推导,而是从局部直接选最优的,
动态规划五部曲:
The?Fibonacci numbers, commonly denoted?F(n)
?form a sequence, called the?Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from?0
?and?1
. That is,
F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1.
class Solution(object):
def fib(self, n):
"""
:type n: int
:rtype: int
"""
"""
# Recursive
if n<2:
return n
return self.fib(n-1) + self.fib(n-2)
"""
# 排除 Corner Case
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(object):
def fib(self, n):
"""
:type n: int
:rtype: int
"""
if n<2:
return n
return self.fib(n-1) + self.fib(n-2)