On a staircase, the i
-th step has some non-negative cost cost[i]
assigned (0 indexed).javascript
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.html
Example 1:java
Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
Example 2:git
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:github
cost
will have a length in the range[2, 1000]
.- Every
cost[i]
will be an integer in the range[0, 999]
.
这道题应该算是以前那道 Climbing Stairs 的拓展,这里不是求步数,而是每一个台阶上都有一个 cost,让咱们求爬到顶端的最小 cost 是多少。换汤不换药,仍是用动态规划 Dynamic Programming 来作。这里定义一个一维的 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])post
最后返回最后一个数字dp[n]便可,参见代码以下:优化
解法一:spa
class Solution { public: int minCostClimbingStairs(vector<int>& cost) { int n = cost.size(); vector<int> dp(n + 1); 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(); } };
再来看一种 DP 的解法,跟上面的解法很相近,不一样在于 dp 数组长度为n,其中 dp[i] 表示到第 i+1 层的最小 cost,分别初始化 dp[0] 和 dp[1] 为 cost[0] 和 cost[1]。而后从 i=2 处开始遍历,此时更新思路是,要爬当前的台阶,确定须要加上当前的 cost[i],那么仍是要从前一层或者前两层的台阶上跳上来,选择 dp 值小的那个,因此递归式以下:code
dp[i] = cost[i] + min(dp[i- 1], dp[i - 2])
最后在最后两个dp值中选择一个较小的返回便可,参见代码以下:
解法二:
class Solution { public: int minCostClimbingStairs(vector<int>& cost) { int n = cost.size(); vector<int> dp(n); dp[0] = cost[0]; dp[1] = cost[1]; for (int i = 2; i < n; ++i) { dp[i] = cost[i] + min(dp[i- 1], dp[i - 2]); } return min(dp[n - 1], dp[n - 2]); } };
咱们能够对空间复杂度进行优化,经过前面的分析咱们能够发现,当前的 dp 值仅仅依赖前面两个的值,因此没必要把整个 dp 数组都记录下来,只需用两个变量a和b来记录前两个值,而后不停的用新获得的值来覆盖它们就行了。初始化a和b均为0,而后遍历 cost 数组,首先将a和b中较小值加上 num 放入临时变量t中,而后把b赋给a,把t赋给b便可,参见代码以下:
解法三:
class Solution { public: int minCostClimbingStairs(vector<int>& cost) { int a = 0, b = 0; for (int num : cost) { int t = min(a, b) + num; a = b; b = t; } return min(a, b); } };
咱们还能够用递归来写,须要优化计算量,即用 HashMap 来保存已经算过了台阶,用的仍是 dp 的思想,参见代码以下:
解法四:
class Solution { public: int minCostClimbingStairs(vector<int>& cost) { unordered_map<int, int> memo; return helper(cost, cost.size(), memo); } int helper(vector<int>& cost, int i, unordered_map<int, int>& memo) { if (memo.count(i)) return memo[i]; if (i <= 1) return memo[i] = cost[i]; return memo[i] = (i == cost.size() ? 0 : cost[i]) + min(helper(cost, i - 1, memo), helper(cost, i - 2, memo)); } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/746
相似题目:
参考资料:
https://leetcode.com/problems/min-cost-climbing-stairs/
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/110109/c-o1-space
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/110111/javascript-and-c-solutions