Problem:
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Explanation:
爬完楼梯需要n步,每次能爬1或2步,每一层楼梯都需要支付一定费用才能继续爬,可以从第一个或第二个楼梯开始爬,求花钱最少的方法。
My Thinking:
对于每一个台阶,如果要经过他,就必须走过他前一个或前前一个台阶,因此到此台阶需要花费的最少钱应该是前一个与前前一个台阶之前花费最少钱的最小值,因此有bp[i]=Math.min(bp[i-1],bp[i-2])+cost[i]
My Solution:
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] bp=new int[cost.length];
bp[0]=cost[0];
bp[1]=cost[1];
int i;
for(i=2;i<bp.length;i++){
bp[i]=Math.min(bp[i-1],bp[i-2])+cost[i];
}
return Math.min(bp[i-1],bp[i-2]);
}
}
Optimum Thinking:
Optimum Solution: