0746. Min Cost Climbing Stairs (E)

Min Cost Climbing Stairs (E)

题目

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.

Example 1:

Input: cost = [10,15,20]
Output: 15
Explanation: Cheapest is: start on cost[1], pay that cost, and go to the top.

Example 2:

Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: Cheapest is: start on cost[0], and only step on 1s, skipping cost[3]. 

Constraints:

  • 2 <= cost.length <= 1000
  • 0 <= cost[i] <= 999

题意

给定一个cost数组,从下标0或1处出发,每次可消耗当前位置对应cost前进1步或2步,求最少需要多少cost前进到数组末尾。

思路

动态规划一把梭。


代码实现

Java

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

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

        return dp[cost.length];
    }
}
posted @ 2021-06-07 22:00  墨云黑  阅读(43)  评论(0编辑  收藏  举报