[LeetCode] 746、使用最小花费爬楼梯

题目描述

数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。

输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6
解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。

解题思路

重要的是理解题意,简单动态规划dp[i] = min(dp[i-1], dp[i-2]) + cost[i]

参考代码

空间复杂度还可以继续优化到O(1)

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int length = cost.size();
        if(length <= 1)
            return 0;
        if(length == 2)
            return min(cost[0], cost[1]);
        
        int dp[length + 1];
        dp[0] = cost[0], dp[1] = cost[1];
        for(int i = 2; i < length; i++){
            dp[i] = min(dp[i-1], dp[i-2]) + cost[i];
        }
        
        return min(dp[length-1], dp[length-2]);
    }
};
发布了390 篇原创文章 · 获赞 576 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/ft_sunshine/article/details/103844592