[LeetCode] 746. Min Cost Climbing Stairs

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: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.

Example 2:

Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.

Constraints:

  • 2 <= cost.length <= 1000
  • 0 <= cost[i] <= 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 层开始,对于第 i 层来说,cost 就是从 i - 2 层爬上来和从 i - 1 层爬上来的 cost 中较小的那一个 + 之前那一层楼梯(第 i 层)的 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 题目总结

posted @ 2020-11-10 02:24  CNoodle  阅读(116)  评论(0编辑  收藏  举报