当前位置:网站首页>746. 使用最小花费爬楼梯-动态规划
746. 使用最小花费爬楼梯-动态规划
2022-06-23 05:48:00 【Mr Gao】
746. 使用最小花费爬楼梯
给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。
示例 1:
输入:cost = [10,15,20]
输出:15
解释:你将从下标为 1 的台阶开始。
- 支付 15 ,向上爬两个台阶,到达楼梯顶部。
总花费为 15 。
示例 2:
输入:cost = [1,100,1,1,1,100,1,1,100,1]
输出:6
解释:你将从下标为 0 的台阶开始。
- 支付 1 ,向上爬两个台阶,到达下标为 2 的台阶。
- 支付 1 ,向上爬两个台阶,到达下标为 4 的台阶。
- 支付 1 ,向上爬两个台阶,到达下标为 6 的台阶。
- 支付 1 ,向上爬一个台阶,到达下标为 7 的台阶。
- 支付 1 ,向上爬两个台阶,到达下标为 9 的台阶。
- 支付 1 ,向上爬一个台阶,到达楼梯顶部。
总花费为 6 。
这一题看似很复杂,其实。我们需要抓住一个点,那就是一个台阶一定由前两个其中一个上来的,我们只需要计算那个cost更小,
解题代码如下:
下面是优化后的代码:
int minCostClimbingStairs(int* cost, int costSize) {
int dp[costSize];
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i <= costSize-1; i++) {
dp[i] = fmin(dp[i - 1] , dp[i - 2] )+cost[i];
}
return fmin(dp[costSize-1],dp[costSize-2]);
}
边栏推荐
- 微信小程序 - 全局监听globalData的某个属性变化,例如监听网络状态切换
- JS to create an array (all elements are objects)
- 回调函数详解
- 解决挖矿病毒 sshd2(redis未设密码、清除crontab定时任务)
- xml schem 记录
- cmder
- Easy EDA learning notes 09 esp32-wroom-32e module esp32-devkitc-v4 development board one click download circuit
- 1161 Merging Linked Lists
- Haas506 2.0 development tutorial -sntp (only versions above 2.2 are supported)
- MySQL5.6 (5.7-8) 基于shardingsphere5.1.1 Sharding-Proxy模式读写分离
猜你喜欢
随机推荐
Qt 中 QVariant 使用总结
Usage Summary of item views and item widgets controls in QT
关于监督
centos7 mysql 记录
idea安装 CloudToolkit 插件
20220621 Three Conjugates of Dual Quaternions
Focusing on the smart city, Huawei cooperates with China Science and technology Xingtu to jointly develop a new digital blue ocean
QT中的item views与Item widgets控件的用法总结
把CSMA/CD、Token Bus、Token Ring说清楚
解决挖矿病毒 sshd2(redis未设密码、清除crontab定时任务)
Machine learning artifact scikit learn minimalist tutorial
asp.net文件下载demo与相关问题的处理
了解学习 JSX 的工作方式
phpStudy设置301重定向
20220621 Dual Quaternion
如何查看本机IP
Summary of business logic security ideas
JS to create an array (all elements are objects)
华为软件测试笔试真题之变态逻辑推理题
/bin/sh no such file or directory问题









