开启动态规划啦拉啦
理论基础
509. 斐波那契数
题目链接
https://leetcode.cn/problems/fibonacci-number/description/
题目描述
思路
1、自己的思路
public int fib(int n) {
if(n==0 || n==1) return n;
return fib(n-1) + fib(n-2);
}
2、答案给的动态规划思路
public int fib(int n) {
if (n <= 1) return n;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int index = 2; index <= n; index++){
dp[index] = dp[index - 1] + dp[index - 2];
}
return dp[n];
}
70. 爬楼梯
题目链接
https://leetcode.cn/problems/climbing-stairs/description/
题目描述
思路
class Solution {
public int climbStairs(int n) {
if(n==1) return 1;
if(n==2) return 2;
int[] dp = new int[n+1];
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
}
746. 使用最小花费爬楼梯
题目链接
https://leetcode.cn/problems/min-cost-climbing-stairs/description/
题目描述
思路
class Solution {
public int minCostClimbingStairs(int[] cost) {
//爬到楼梯顶部,是指爬完楼梯之后还要往上一步
//所以长度要设置为 cost.length+1
int[] dp = new int[cost.length+1];
//从第0个或者第一个往上爬均不需要花费
dp[0] = 0;
dp[1] = 0;
//比如 cost 的大小是2,但是爬上楼梯需要在爬完下标为2的台阶之后再向上爬一层,才到达了楼梯顶部
for (int i = 2; i <= cost.length; i++) {
dp[i] = Math.min(dp[i-1] + cost[i-1],dp[i-2] + cost[i-2]);
}
return dp[cost.length];
}
}
总结
动态规划五部曲
确定dp数组(dp table)以及下标的含义
确定递推公式
dp数组如何初始化
确定遍历顺序
举例推导dp数组