基本概念:
代码随想录:
Dynamic Programming,简称DP,如果某一问题有很多重叠子问题,使用动态规划是最有效的。
所以动态规划中每一个状态一定是由上一个状态推导出来的,这一点就区分于贪心,贪心没有状态推导,而是从局部直接选最优的,
动态规划五部曲:
- 确定dp数组(dp table)以及下标的含义
- 确定递推公式
- dp数组如何初始化
- 确定遍历顺序
- 举例推导dp数组
509. Fibonacci Number
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""""""# Recursiveif n<2:return nreturn self.fib(n-1) + self.fib(n-2)"""# 排除 Corner Caseif 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 nreturn self.fib(n-1) + self.fib(n-2)