On a staircase, thei-th step has some non-negative costcost[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.

这个题其实也不难,唯一恶心的一点是,这题的意思不是走到cost.length - 1个台阶的cost,而是走到cost.length的cost

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int[] res = new int[cost.length + 1];
        res[0] = 0;
        res[1] = 0;

        for(int i = 2; i <= cost.length; i++) {
            res[i] = Math.min(res[i - 1] + cost[i - 1], res[i - 2] + cost[i - 2]);
            res[i] = Math.min(res[i], res[i - 2] + cost[i - 2] + cost[i - 1]);
        }

        return res[res.length - 1];
    }
}

results matching ""

    No results matching ""