当前位置:网站首页>力扣:746. 使用最小花费爬楼梯
力扣:746. 使用最小花费爬楼梯
2022-08-04 05:14:00 【empty__barrel】
力扣:746. 使用最小花费爬楼梯
题目:
给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。
此题有注意点,即:
到达的是楼顶而不是最后一个台阶。到达楼顶的方式是最后一个台阶走一步即数组最后一个值,或者倒数第二个台阶走两步到达楼顶,即数组倒数第二个值。一开始我还以为到达的是最后一个楼梯。因此最后写返回值时如下:
return min(dp[cost.size()-3],dp[cost.size()-2]);
普通代码:
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
vector<int>dp(cost.size());
dp[0] = cost[0];
dp[1] = cost[1];
for(int i = 2; i < cost.size(); ++i){
dp[i] = min(dp[i-1],dp[i-2])+cost[i];
}
return min(dp[cost.size()-1],dp[cost.size()-2]);
}
};
代码:其实只需要维护两个数值即可
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int dp[2];
dp[0] = cost[0];
dp[1] = cost[1];
for(int i = 2; i < cost.size(); ++i){
int m = min(dp[0],dp[1])+cost[i];
dp[0] = dp[1];
dp[1] = m;
}
return min(dp[1],dp[0]);
}
};
边栏推荐
- Hangdian Multi-School-Slipper- (tree map conversion + virtual point mapping)
- C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.1 Arrays are not pointers
- 【评价类模型】Topsis法(优劣解距离法)
- 入坑软件测试的经验与建议
- QT 如何识别文件的编码格式
- There is an 8 hour difference between the docker installation of mysql and the host.
- 使用Patroni回调脚本绑定VIP的坑
- flink cdc一启动,源端Oracle那台服务器的CPU就飙升到80%以上,会是啥原因呢?
- 高性能高可靠性高扩展性分布式防火墙架构
- OpenGL绘制圆
猜你喜欢
随机推荐
烧录场景下开发如何进行源代码保密工作
Gartner 权威预测未来4年网络安全的8大发展趋势
21 days learning challenge 】 【 sequential search
C Expert Programming Chapter 5 Thinking about Linking 5.3 5 Special Secrets of Library Linking
[Cocos] cc.sys.browserType可能的属性
Interesting Kotlin 0x0E: DeepRecursiveFunction
Use Patroni callback script to bind VIP pit
Bolb analysis of image processing (1)
C专家编程 第5章 对链接的思考 5.4 警惕Interpositioning
Introduction and application of go module
读者让我总结一波 redis 面试题,现在肝出来了
3000 words, is take you understand machine learning!
【SemiDrive源码分析】【MailBox核间通信】47 - 分析RPMSG_IPCC_RPC 方式 单次传输的极限大小 及 极限带宽测试
Write golang simple C2 remote control based on gRPC
C专家编程 第5章 对链接的思考 5.6 轻松一下---看看谁在说话:挑战Turning测验
mysql index notes
力扣题解8/3
C专家编程 第5章 对链接的思考 5.3 函数库链接的5个特殊秘密
关于yolo7和gpu
How to open a CITIC Securities online account?is it safe?