当前位置:网站首页>力扣: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]);
}
};
边栏推荐
- Shocked, 99.9% of the students didn't really understand the immutability of strings
- Structure function exercise
- sql server如何得到本条记录与上一条记录的差异,即变动值
- SLSA 框架与软件供应链安全防护
- 商城系统APP如何开发 都有哪些步骤
- 败给“MySQL”的第60天,我重振旗鼓,四面拿下蚂蚁金服offer
- C Expert Programming Chapter 5 Thinking about Linking 5.3 5 Special Secrets of Library Linking
- 入坑软件测试的经验与建议
- C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.1 数组并非指针
- 深度学习21天——准备(环境配置)
猜你喜欢
企业需要知道的5个 IAM 最佳实践
震惊,99.9% 的同学没有真正理解字符串的不可变性
[Evaluation model] Topsis method (pros and cons distance method)
word 公式编辑器 键入技巧 | 写数学作业必备速查表
结构体函数练习
【C语言进阶】程序环境和预处理
高性能高可靠性高扩展性分布式防火墙架构
Explain detailed explanation and practice
Teenage Achievement Hackers Need These Skills
Turn: Management is the love of possibility, and managers must have the courage to break into the unknown
随机推荐
8. Haproxy builds a web cluster
About yolo7 and gpu
px、em、rem的区别
Converts XML tags to TXT format (voc conversion for yolo convenient training)
Towards Real-Time Multi-Object Tracking(JDE)
获取单选框选中内容
BFC、IFC、GFC、FFC概念理解、布局规则、形成方法、用处浅析
如何打造一篇优秀的简历
心余力绌:企业面临的软件供应链安全困境
入坑软件测试的经验与建议
想低成本保障软件安全?5大安全任务值得考虑
Hangdian Multi-School-Slipper- (tree map conversion + virtual point mapping)
深度学习环境配置
The difference between px, em, and rem
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.3 什么是声明,什么是定义
System design. Seckill system
结构体指针知识要点总结
3000 words, is take you understand machine learning!
C专家编程 第5章 对链接的思考 5.4 警惕Interpositioning
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.5 数组和指针的其他区别