LeetCode 746. Min Cost Climbing Stairs

DP解法:定义一个dp数组,dp[i]为到达第i层的最小花费,dp[i]仅与dp[i-1]和dp[i-2]和相应层的cost值有关,满足:dp[i] = min(dp[i-2] + cost[i-2] , dp[i-1] + cost[i-1]);由于i大于等于2,则将dp[0] = dp[1] = 0。

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();
        vector<int> sumCost(n + 1);
         sumCost[0] = sumCost[1] = 0;
        for (int i = 2; i < n; ++i) 
            sumCost[i] = min(sumCost[i-2] + cost[i-2], sumCost[i-1] + cost[i-1]);
        return min(sumCost[n-2] + cost[n-2],sumCost[n-1] + cost[n-1]);
    }
};
    原文作者:alexssssu
    原文地址: https://www.jianshu.com/p/1b06905ae5cb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞