【12月22日】LeetCode刷题日志(五):Min Cost Climbing Stairs

题目描述
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;i2]+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,实践学习)