力扣746. 使用最小花费爬楼梯

题目来源(力扣):

https://leetcode.cn/problems/min-cost-climbing-stairs/description/

题目描述:

给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。

基本思路:

爬楼梯题目的基础上增加的花费的概念,实际上的思路是一致的。
注意最后要求的是到“楼梯顶部”的最低花费。
楼梯下标从0开始,因此楼梯顶部应该是n(以及n+1,n+2……及其之后的阶层)。

代码实现:

class Solution
{
public:
    int minCostClimbingStairs(vector<int> &cost)
    {
        int n = cost.size();

        // 1.确定dp数组及其含义
        // dp[i]表示到达第i级台阶所需要的最小花费是dp[i]
        vector<int> dp(cost.size() + 3);

        // 2.确定递推公式
        // dp[i]=min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]);

        // 3.初始化
        dp[0] = 0;
        dp[1] = 0;

        // 4.确定遍历顺序
        // 由递推式可知应该从前往后进行
        for (int i = 2; i <= n; i++)
        {
            dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
        }

        // 5.打印dp数组,确认是否和预期的相同
        //  for(int i=0;i<=n;i++)
        //      cout<<dp[i]<<" ";

        // 将第n级楼梯作为“楼梯顶部”
        return dp[n];
    }
};

时间复杂度

O(n)

posted @ 2024-11-25 10:46  HB_Computer  阅读(37)  评论(0)    收藏  举报