问题描述:
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
走台阶,登每级台阶有一个“价格”,一次可以走1或2级,求登顶的最小费用
思路:
典型的动态规划题
登上第i级台阶的最小费用=MIN(登上第i-2级台阶的最小费用,登上第i-1级台阶的最小费用)+ 第i级台阶的费用
最终要的结果是MIN(登上第n-1级台阶的最小费用,登上第n级台阶的最小费用)
代码如下:
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] opt=new int[cost.length];
opt[0]=cost[0];
opt[1]=cost[1];
for(int i=2; i<cost.length; i++){
opt[i]=Math.min(opt[i-2], opt[i-1])+cost[i];
}
return Math.min(opt[cost.length-1], opt[cost.length-2]);
}
}
时间复杂度:O(n)