zoukankan      html  css  js  c++  java
  • [LeetCode] 746. 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.

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

    使用最小花费爬楼梯。

    数组的每个下标作为一个阶梯,第 i 个阶梯对应着一个非负数的体力花费值 cost[i](下标从 0 开始)。

    每当你爬上一个阶梯你都要花费对应的体力值,一旦支付了相应的体力值,你就可以选择向上爬一个阶梯或者爬两个阶梯。

    请你找出达到楼层顶部的最低花费。在开始时,你可以选择从下标为 0 或 1 的元素作为初始阶梯。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/min-cost-climbing-stairs
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这道题跟70题很像,但是注意题目的区别。这道题是在问爬楼梯的最小花费。每层楼梯是有一个花费 cost[i] 的,同时这道题可以允许你从第 0 层或者第 1 层开始爬。

    思路还是动态规划。这里我们还是创建一个长度为 N + 1 的数组记录 DP 的中间结果。这里 DP 的定义是到某一级台阶的花费是 dp[i]。既然可以从第 0 层或者第 1 层开始爬,那么从第 2 层开始,cost就是从 i - 2 层爬上来和从 i - 1 层爬上来的 cost 中较小的那一个 + 之前那一层楼梯的 DP 值。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int minCostClimbingStairs(int[] cost) {
     3         int n = cost.length;
     4         int[] dp = new int[n + 1];
     5         for (int i = 2; i <= n; i++) {
     6             dp[i] = Math.min(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1]);
     7         }
     8         return dp[n];
     9     }
    10 }

    不使用额外空间的做法。

     1 class Solution {
     2     public int minCostClimbingStairs(int[] cost) {
     3         int a = 0;
     4         int b = 0;
     5         for (int c : cost) {
     6             int cur = Math.min(a, b) + c;
     7             a = b;
     8             b = cur;
     9         }
    10         return Math.min(a, b);
    11     }
    12 }

    相关题目

    70. Climbing Stairs

    509. Fibonacci Number

    746. Min Cost Climbing Stairs

    1137. N-th Tribonacci Number

    LeetCode 题目总结

  • 相关阅读:
    腾讯云挂载文件服务器节点
    OpsManage 安装
    centos7 安装mysql
    vs code 新建vue项目
    Centos7 安装supervisor
    腾讯云Centos7 安装nginx
    django 生成pdf
    VM安装虚拟机
    ACM/ICPC 之 Floyd练习六道(ZOJ2027-POJ2253-POJ2472-POJ1125-POJ1603-POJ2607)
    ACM/ICPC 之 Floyd范例两道(POJ2570-POJ2263)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13951907.html
Copyright © 2011-2022 走看看