[LeetCode]746. Min Cost Climbing Stairs

[LeetCode]746. Min Cost Climbing Stairs

题目描述

[LeetCode]746. Min Cost Climbing Stairs_第1张图片

思路

不能存在连续两个不选择的数,所以每次更新的公式为
min(dp[i - 1] + cost[i], dp[i - 2], cost[i - 1])
考虑选择当前位置,或者选择前一位置的最优结果

代码

#include
#include
#include

using namespace std;

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        if (cost.size() == 2) return min(cost[0], cost[1]);
        if (cost.size() == 3) return min(cost[0] + cost[2], cost[1]);
        vector<int> dp(cost.size());
        dp[0] = cost[0], dp[1] = min(cost[0], cost[1]), dp[2] = min(cost[0] + cost[2], cost[1]);
        for (int i = 3; i < cost.size(); ++i)
            dp[i] = min(dp[i - 1] + cost[i], dp[i - 2] + cost[i - 1]);
        return dp[cost.size() - 1];
    }
};

int main() {
    vector<int> cost = { 10,15,20,10 };
    Solution s;

    cout << s.minCostClimbingStairs(cost) << endl;

    system("pause");
    return 0;
}

你可能感兴趣的:(leetcode)