解题思路
我们爬上第n级台阶所花费的最小费用即为从第n-1级台阶所花的费用加上cost[n-1],或者从第n-2级台阶所花费的最小费用加上cost[n-2],因此我们只需要一个长度为3的数组即可完成计算,有一点需要注意的地方是爬上最后一级台阶之后还要再爬一次才能到顶部,因此,在遍历cost数组时,最后一级台阶的费用也要使用,刚开始用了一个dp[n]的数组,后来经过优化,使用长度为3的数组即可解决问题,代码如下:
代码
class Solution {
public int minCostClimbingStairs(int[] cost) {
if(cost.length ==2){
return Math.min(cost[0], cost[1]);
}
int i=2;
int length = cost.length;
int[] dp = new int[3];
while(i<=length){
dp[2] = Math.min(dp[1]+cost[i-1], dp[0]+cost[i-2]);
dp[0] = dp[1];
dp[1] = dp[2];
i++;
}
return dp[2];
}
}