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;
    }
};

猜你喜欢

转载自blog.csdn.net/shine10076/article/details/82502827
6.1
今日推荐