Day 6.1 最小代价爬楼梯

problem describe:
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.
数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 costi
每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
解答:
明显的,这是一道动态规划的问题,跑到第i层楼梯的最小解是从上一层或上两层到此楼梯的代价花费较小的一个,如果我们假设爬到第i层楼梯的最小代价为f[i], 那么它就可以表示为
f[i] = cost[i]+min(f[i-1],f[i-2]).最后我们只要比较一下第n层与第n-1层的代价开销就可以了
代码如下

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();
        int *f=new int [n];
        f[0]=cost[0];
        f[1]=cost[1];
        for (int i=2;i<n;i++)
        {
            f[i]=cost[i]+min(f[i-1],f[i-2]);
        }
        return (f[n-1]<f[n-2])?f[n-1]:f[n-2];

    }
    int min(int a,int b)
    {
        if(a>b) return b;
        return a;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值