Problem:
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:
1 2 3 |
Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top. |
Example 2:
1 2 3 |
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:
cost
will have a length in the range[2, 1000]
.- Every
cost[i]
will be an integer in the range[0, 999]
.
题目大意:
有一个楼梯,要离开i层需要付cost[i]的费用,每次可以爬1层或2层。问你最少花多少钱能够达到顶楼。
Solution:
C++ / Recursion + Memorization 记忆化递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua // Runtime: 9 ms class Solution { public: int minCostClimbingStairs(vector<int>& cost) { vector<int> m(cost.size() + 1); return dp(cost, m, cost.size()); } private: // min cost to climb to i-th step int dp(vector<int>& cost, vector<int>& m, int i) { if (i <= 1) return 0; if (m[i] > 0) return m[i]; return m[i] = min(dp(cost, m, i - 1) + cost[i - 1], dp(cost, m, i - 2) + cost[i - 2]); } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua // Runtime: 9 ms class Solution { public: int minCostClimbingStairs(vector<int>& cost) { vector<int> m(cost.size() + 1); return min(dp(cost, m, cost.size() - 1), dp(cost, m, cost.size() - 2)); } private: // min cost before leaving i-th step int dp(vector<int>& cost, vector<int>& m, int i) { if (i < 0) return 0; if (m[i] > 0) return m[i]; return m[i] = min(dp(cost, m, i - 1), dp(cost, m, i - 2)) + cost[i]; } }; |
C++ / DP 动态规划
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Author: Huahua // Runtime: 9 ms class Solution { public: int minCostClimbingStairs(vector<int>& cost) { const int n = cost.size(); vector<int> dp(n, INT_MAX); // d[i] min cost before leaving i dp[0] = cost[0]; dp[1] = cost[1]; for (int i = 2; i < n; ++i) dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]; // We can reach top from either n - 1, or n - 2 return min(dp[n - 1], dp[n - 2]); } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua // Runtime: 12 ms class Solution { public: int minCostClimbingStairs(vector<int>& cost) { // dp[i] : min cost to climb to n-th step vector<int> dp(cost.size() + 1, 0); for (int i = 2; i <= cost.size(); ++i) dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); return dp[cost.size()]; } }; |
O(1) Space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Author: Huahua // Runtime: 15 ms class Solution { public: int minCostClimbingStairs(vector<int>& cost) { int dp1 = 0; int dp2 = 0; for (int i = 2; i <= cost.size(); ++i) { int dp = min(dp1 + cost[i - 1], dp2 + cost[i - 2]); dp2 = dp1; dp1 = dp; } return dp1; } }; |