746. Min Cost Climbing Stairs (dp)

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

You can either start from the step with index 0, or the step with index 1.

Return the minimum cost to reach the top of the floor.

Classical dp question.

you can either climb one or two steps. We can simply set the dp[i] to be the minimum cost to reach index i and we will return dp[cost.size()]. It is a pretty intuitive solution.

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

Can we optimize the space complexity? 

Yes, actually it can be reduced to O(1). How? 

As we can see the dp[i] only relies on dp[i - 1] and dp[i - 2], we can simply use two variable to replace the whole dp array. 

  

 

you can see the a, b, c represent dp[i - 2], dp[i - 1] and dp[i] respectively. We just need to swap the value of a, b, c and achieve the same output as using dp array.  

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值