LeetCode#746 Min Cost Climbing Stairs (week16)

week16

题目

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
这里写图片描述
Note:
1. cost will have a length in the range [2, 1000].
2. Every cost[i] will be an integer in the range [0, 999].
原题地址:https://leetcode.com/problems/min-cost-climbing-stairs/description/

解析

题目要求给定每一阶楼梯阶梯的代价,每次可以走一层或两层,求从最底部爬到最顶部的最小代价。
思路:该题属于动态规划问题,给定一个爬楼梯方案,对于某一级的阶梯,我们只可以选择走或者不走。我们可以用一个sum[n][2]的数组保存到每一阶楼梯时选择走该级阶梯的最小总代价以及不走该级阶梯的最小总代价。则我们可以得到每一阶阶梯的公式:
不走该级阶梯的最小代价为sum[i][0]=sum[i - 1][1],即该级阶梯不走,则上一级阶梯必须走。
走该级阶梯的最小代价为sum[i][1]=min(sum[i - 1][0] + cost[i], sum[i - 1][1] + cost[i]),即该级阶梯走,则上一级阶梯可走可不走,取二者中的较小者。
最后得到的最高级阶梯中的两者中较小的一个即为答案。

代码

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int length = cost.size();
        if (length == 0) {
            return 0;
        }
        int** sum = new int*[length];
        for (int i = 0; i < length; ++i) {
            sum[i] = new int[2];
        }
        sum[0][0] = 0;
        sum[0][1] = cost[0];
        for (int i = 1; i < length; ++i) {
            sum[i][0] = sum[i - 1][1];
            sum[i][1] = min(sum[i - 1][0] + cost[i], sum[i - 1][1] + cost[i]);
        }
        return min(sum[length - 1][0], sum[length - 1][1]);
    }
    int min(int a, int b) {
        return a < b ? a : b;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值