这是leetCode上的一道题(地址)
数组的每个索引作为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。
每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
示例 1:
输入: cost = [10, 15, 20]
输出: 15
解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
示例 2:
输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6
解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。
一看题目,就是要用动态规划。
示例1 很有意思,最小值是15,也就是直接从第二个元素开始,不用管最后一个元素。
也就是说,示例1,比较 10 + 20 和 15,取较小的一个。
由此,可以看出,题目的用意,是从两种结果中取最小值
A :走到最后一个台阶所用最小花费
B:走到倒数第二阶所用的最小花费
从 A B 中取最较小的那个就是题目的所求。
public int minCostClimbingStairs(int[] cost) {
if(null == cost || cost.length == 1){
return 0;
}
int len = cost.length;
if(len == 2){
return Math.min(cost[0], cost[1]);
}
if(len == 3){
return Math.min(cost[2], cost[0] + cost[1]);
}
int ppre = cost[0]; // 上上个值
int pre = cost[1]; // 上一个值
for(int i = 2; i < len; i++){
// 计算到第i阶最小花费,即 到 i -1阶和i-2阶中取较小的,加上第i 阶的花费
int min = Math.min(ppre, pre); // 取较小的那个
ppre = pre; // 状态转移
pre = min + cost[i]; // 算出第i阶的花费,并赋值给pre
}
return Math.min(ppre, pre);
}
想明白了,其实不复杂,最终回顾的时候,我发现,最后一个for循环就解决所有问题了
前面的两个if可省略,代码优化如下
public int minCostClimbingStairs(int[] cost) {
if(null == cost || cost.length == 1){
return 0;
}
int len = cost.length;
int ppre = cost[0];
int pre = cost[1];
for(int i = 2; i < len; i++){
int min = Math.min(ppre, pre);
ppre = pre;
pre = min + cost[i];
}
return Math.min(ppre, pre);
}
我更愿意相信,精简的代码,不是一蹴而就的,哈哈!