其他分享
首页 > 其他分享> > [LeetCode] 746. Min Cost Climbing Stairs

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

使用最小花费爬楼梯。

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