LeetCode 746. 使用最小花费爬楼梯C#
原题链接
简单
作者:
hpstory
,
2022-07-04 10:32:30
,
所有人可见
,
阅读 152
C# 代码
public class Solution {
public int MinCostClimbingStairs(int[] cost) {
int[] dp = new int[cost.Length];
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i < cost.Length; i++){
dp[i] = Math.Min(dp[i - 1], dp[i - 2]) + cost[i];
}
return Math.Min(dp[^1], dp[^2]);
}
}
C# 常数空间代码
public class Solution {
public int MinCostClimbingStairs(int[] cost) {
int dp0 = cost[0];
int dp1 = cost[1];
for(int i = 2; i < cost.Length; i++){
int dpi = Math.Min(dp0, dp1) + cost[i];
dp0 = dp1;
dp1 = dpi;
}
return Math.Min(dp0, dp1);
}
}