动态规划中每一个状态一定是由上一个状态推导出来的。
而贪心没有状态推导,是从局部直接选最优的。
动态规划五步走:
- 确定dp数组(dp table)以及下标的含义
- 确定递推公式
- dp数组如何初始化
- 确定遍历顺序
- 举例推导dp数组
509.斐波那契数
class Solution {
public int fib(int n) {
if(n==0){
return 0;
}
if(n==1){
return 1;
}
int lastLast =0, last=1;
for(int i=2, cur; i<=n; i++){
cur = lastLast + last;
lastLast = last;
last = cur;
}
return last;
}
}
70. 爬楼梯
class Solution {
public int climbStairs(int n) {
if(n<=2) return n;
int a=1, b=2,sum=0;
for(int i=3; i<=n; i++){
sum = a+b;
a = b;
b = sum;
}
return sum;
}
}
class Solution {
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
int[] dp = new int[n+1];
dp[0]=0;
dp[1]=0;
for(int i = 2; i<=n; i++){
dp[i] = Math.min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]);
}
return dp[n];
}
}