ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 746. Min Cost Climbing Stairs

2020-11-10 02:31:28  阅读:391  来源: 互联网

标签:cost 746 Min int step Cost Climbing 100 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].

使用最小花费爬楼梯。

这道题跟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

746. Min Cost Climbing Stairs

LeetCode 题目总结

标签:cost,746,Min,int,step,Cost,Climbing,100,Stairs
来源: https://www.cnblogs.com/cnoodle/p/13951907.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有