题目地址:Min Cost Climbing Stairs - LeetCode
LeetCode 动态规划(Dynamic programming)系列题目:LeetCode 动态规划(Dynamic programming)系列题目
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:
- cost will have a length in the range [2, 1000].
- Every cost[i] will be an integer in the range [0, 999].
这是一道经典的动态规划的题目,是爬楼梯的变种。
动态规划从前往后的Python解法如下:
此解法可以优化,不用数组,只用2个临时变量
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
length=len(cost)
if length==0 or length==1:
return 0
elif length==2:
return min(cost[0],cost[1])
count=[0 for i in range(0,length+1)]
count[0]=0
count[1]=0
for i in range(2,length+1):
count[i]=min(count[i-2]+cost[i-2],count[i-1]+cost[i-1])
return count[length]
C++解法:
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost){
auto n=cost.size();
vector<int> dp(n);
dp[0]=cost[0];
dp[1]=cost[1];
for (auto i=2; i<n; ++i)
dp[i]=cost[i]+min(dp[i-2],dp[i-1]);
return min(dp[n-2],dp[n-1]);
}
};
Java解法如下:
class Solution {
public int minCostClimbingStairs(int[] cost){
int twoStepBefore = cost[0];
int oneStepBefore = cost[1];
int curr = 0;
for(int i = 2;i< cost.length;i++){
curr = Math.min(twoStepBefore,oneStepBefore) + cost[i];
twoStepBefore = oneStepBefore;
oneStepBefore = curr;
}
return Math.min(oneStepBefore,twoStepBefore);
}
}

本文介绍了一道LeetCode经典动态规划题目“爬楼梯”的解题思路与算法实现,通过Python、C++及Java三种语言展示如何找到从楼梯底部到达顶部的最小成本路径。
319

被折叠的 条评论
为什么被折叠?



