746. Min Cost Climbing Stairs 爬楼梯的最小损失

题目链接

tag:

  • Easy;
  • Dynamic Programming;

question:
  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.

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].

Note:

  1. cost will have a length in the range [2, 1000].
  2. Every cost[i] will be an integer in the range [0, 999].

思路:
  这道题是之前那道Climbing Stairs的拓展,这里不是求步数,而是每个台阶上都有一个cost,让我们求爬到顶端的最小cost是多少。换汤不换药,还是用动态规划DP来做。这里我们定义一个一维的dp数组,其中dp[i]表示爬到第i层的最小cost,然后我们来想dp[i]如何推导。我们来思考一下如何才能到第i层呢?是不是只有两种可能性,一个是从第i-2层上直接跳上来,一个是从第i-1层上跳上来。不会再有别的方法,所以我们的dp[i]只和前两层有关系,所以可以写做如下:

    dp[i] = min(dp[i- 2] + cost[i - 2], dp[i - 1] + cost[i - 1])

最后我们返回最后一个数字dp[n]即可,参见代码如下:

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();
        vector<int> dp(n+1, 0);
        for (int i=2; i<n+1; ++i) {
            dp[i] = min(dp[i-2]+cost[i-2], dp[i-1]+cost[i-1]);
        }
        return dp.back();
    }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,173评论 0 10
  • 我知道这世界上再也没有一个人像她一样对他好了! 我知道这世界上再也没有一个人像你一样对我们好了! 你走了,...
    孟夏闰月闻麦香阅读 2,405评论 1 7
  • 绘本:《蹦》、《大声回答哎》、《敲敲门谁在家》、《脸脸,各种各样的脸》,在读哭的脸时,我摆着很可怜哭的表情,宝宝还...
    嘟嘟嘀嘀阅读 1,445评论 0 0
  • 月缺了又圆 星星隐了又现 就像我们的爱情 在这茫茫的天地间 我来了又走 依然计算着相聚的时间 月圆了又缺 但是昼夜...
    王不烦阅读 1,256评论 0 1

友情链接更多精彩内容