class Solution { public: int minCostClimbingStairs(vector<int>& cost) { vector<int> totol(cost.size(), 0); totol[0] = cost[0], totol[1] = cost[1]; for (int i = 2; i < cost.size(); i++) { totol[i] = min(totol[i - 2] + cost[i], totol[i - 1] +cost[i]); } return min(totol[cost.size() - 1], totol[cost.size() - 2]); } };
下面是C#版本的:
public class Solution { public int MinCostClimbingStairs(int[] cost) { var total = new List<int>(); total.Add(cost[0]);//第0阶台阶的最小总花费 total.Add(Math.Min(cost[1], cost[0] + cost[1]));//第1节台阶的最小总花费 for (int i = 2; i < cost.Length; i++) { //当前台阶的最小总花费=当前台阶的直接花费+ min(当前-1节总花费 , 当前-2节总花费) total.Add(cost[i] + Math.Min(total[i - 1], total[i - 2])); } //最后上到楼梯顶,可能踩倒数第一节或者倒数第二节。选择其中小的 return Math.Min(total[cost.Length - 1], total[cost.Length - 2]); } }