当前位置:网站首页>力扣: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]);
}
};
边栏推荐
- 使用Patroni回调脚本绑定VIP的坑
- Tactile intelligent sharing - SSD20X realizes upgrade display progress bar
- 10 Convolutional Neural Networks for Deep Learning 3
- [21 Days Learning Challenge] Image rotation problem (two-dimensional array)
- Hangdian Multi-School-Slipper- (tree map conversion + virtual point mapping)
- C Expert Programming Chapter 5 Thinking about Linking 5.1 Libraries, Linking and Loading
- 路网编辑器技术预研
- 入坑软件测试的经验与建议
- 结构体指针知识要点总结
- px、em、rem的区别
猜你喜欢

Typora 使用保姆级教程 | 看这一篇就够了 | 历史版本已被禁用

Converts XML tags to TXT format (voc conversion for yolo convenient training)

leetcode 12. 整数转罗马数字

3面头条,花7天整理了面试题和学习笔记,已正式入职半个月
![[C language advanced] program environment and preprocessing](/img/ac/a13dd2cc47136d4938b6fc7fad660c.png)
[C language advanced] program environment and preprocessing

The symbol table

腾讯136道高级岗面试题:多线程+算法+Redis+JVM

7-1 LVS+NAT load balancing cluster, NAT mode deployment

如何将 DevSecOps 引入企业?

结构体函数练习
随机推荐
Interesting Kotlin 0x0E: DeepRecursiveFunction
Gartner 权威预测未来4年网络安全的8大发展趋势
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.2 我的代码为什么无法运行
【SemiDrive源码分析】【MailBox核间通信】47 - 分析RPMSG_IPCC_RPC 方式 单次传输的极限大小 及 极限带宽测试
企业需要知道的5个 IAM 最佳实践
Tactile intelligent sharing - SSD20X realizes upgrade display progress bar
Programming hodgepodge (4)
C专家编程 第5章 对链接的思考 5.6 轻松一下---看看谁在说话:挑战Turning测验
Towards Real-Time Multi-Object Tracking(JDE)
OpenGL绘制圆
转:管理是对可能性的热爱,管理者要有闯进未知的勇气
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.4 使声明与定义相匹配
Redis common interview questions
3面头条,花7天整理了面试题和学习笔记,已正式入职半个月
力扣题解8/3
Chapter 5 C programming expert thinking 5.4 alert Interpositioning of links
el-Select selector bottom fixed
What are the functions of mall App development?
Will the 2023 PMP exam use the new version of the textbook?Reply is here!
商城系统APP如何开发 都有哪些步骤