【LeetCode】746. Min Cost Climbing Stairs

题目描述:数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 costi

每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。

您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。

示例 1:

输入: cost = [10, 15, 20]
输出: 15

示例 2:

输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6 解释:
最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。

注意:

cost 的长度将会在 [2, 1000]。
每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。
【Tips】:动态规划问题

#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm> 
using namespace std;

class Solution {
public:
/*使用最小花费爬楼梯*/
    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();
        vector<int> cm(n + 1); //Top means above the last stair

                               //Edge Case
        if (n<2) return 0;

        //Can either start from index 0 or 1
        cm[0] = 0;
        cm[1] = 0;

        //DP to find the minimum cost to reach the last stair or second last stair
        for (int i = 2; i <= n; i++)
            cm[i] = min(cm[i - 2] + cost[i - 2], cm[i - 1] + cost[i - 1]);

        //Cost to reach the stair above the last
        return cm[n];
    }
};

int main()
{
    vector<int> tmp(10);
    tmp[0] = 1; tmp[1] = 100; tmp[2] = 1; tmp[3] = 1; tmp[4] = 1;
    tmp[5] = 100; tmp[6] = 1; tmp[7] = 1; tmp[8] = 100; tmp[9] = 1;
    //int n = sizeof(tmp) / sizeof(tmp[0]);

    Solution solu;
    int test = solu.minCostClimbingStairs(tmp);
    cout << test<<endl;
    //getchar();
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值