题目描述
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.
题目分析
这个题目其实和(四)很像,参照(四)的思路,进行动态规划求解。
对于第i天而言,令函数M表示到i天cost最低。则M[i]可以表示为:
M[i] =Math.min(M[i-2]+cost[i-2], M[i-1]+cost[i-1]), i>=2。
且M[0]=M[1]=0。
代码实现
public int minCostClimbingStairs(int[] cost) {
int len = cost.length;
int[] M = new int[len];
M[0] = 0;
M[1] = 0;
for(int i=2;i<len;i++){
M[i] =Math.min(M[i-2]+cost[i-2], M[i-1]+cost[i-1]);
}
return Math.min(M[len-1]+cost[len-1], M[len-2]+cost[len-2]);
}

本文介绍了一种通过动态规划算法解决楼梯成本最小化问题的方法。该问题要求从楼梯底部到达顶部所需成本最低,每次可以上一阶或两阶。文章详细解析了动态规划方程,并给出了具体的Java代码实现。
350

被折叠的 条评论
为什么被折叠?



