动态规划解题步骤
- 确定dp数组(dp table)以及下标的含义
- 确定递推公式
- dp数组如何初始化
- 确定遍历顺序
- 举例推导dp数组
509. 斐波那契数
显然dp[i]
代表fib[i]
,fib[i] = fib[i-1] + fib[i-2]
,fib[0] = 0, fib[1] = 1
,遍历从前往后遍历即可。下面的代码优化了空间复杂度,但思路是一致的。
class Solution {
public int fib(int n) {
if(n <= 1) return n;
int pre = 0, cur = 1;
for(int i = 2; i <= n; i++){
int sum = pre + cur;
pre = cur;
cur = sum;
}
return cur;
}
}
70. 爬楼梯
这道题与斐波那契数列完全一致,按照五步走。dp[i]
代表了爬到第i
个台阶的方法数,显然第i层台阶可以从i-1,和i-2爬过来,即dp[i] = dp[i-1] + dp[i-2]
。初始值保证dp[2]正确就行。
class Solution {
public int climbStairs(int n) {
// dp[i]代表i阶楼梯有多少种方法
// dp[0] = dp[1] = 1,可以验证其正确性,因为dp[2] = dp[0] + dp[1] = 2是正确的
if(n <= 1) return 1;
int pre = 1, cur = 1;
for(int i = 2; i <= n; i++){
int sum = pre + cur;
pre = cur;
cur = sum;
}
return cur;
}
}
746. 使用最小花费爬楼梯
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] dp = new int[cost.length+1];
dp[0] = 0; dp[1] = 0;
for(int i = 2; i < dp.length; i++){
dp[i] = Math.min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]);
}
return dp[dp.length-1];
}
}
标签:Part01,32,Solution,fib,int,length,cost,Day,dp
From: https://www.cnblogs.com/12sleep/p/18341634