第九章 动态规划part01
大纲
● 理论基础
● 509. 斐波那契数
● 70. 爬楼梯
● 746. 使用最小花费爬楼梯
理论基础
- 五部曲
- 确定dp数组(dp table)以及下标的含义
- 确定递推公式
- dp数组如何初始化
- 确定遍历顺序
- 举例推导dp数组
leetcode 509
斐波那契数
class Solution {
public int fib(int n) {
if (n <= 1) return n;
int a = 0, b = 1, c = 0;
for (int i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
}
leetcode 70
爬楼梯
class Solution {
public int climbStairs(int n) {
if (n <= 2) return n;
int a = 1, b = 2, c = 0;
for (int i = 3; i <= n; i ++) {
c = a + b;
a = b;
b = c;
}
return b;
}
}
leetcode 746
使用最小花费爬楼梯
class Solution {
public int minCostClimbingStairs(int[] cost) {
int len = cost.length;
int[] dp = new int[len + 1];
for (int i = 2; i <= len; i++)
dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
return dp[len];
}
}