当前位置:网站首页>力扣: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]);
}
};
边栏推荐
- [One step in place] Jenkins installation, deployment, startup (complete tutorial)
- C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.1 Arrays are not pointers
- C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.4 Matching declarations to definitions
- mysql index notes
- 想低成本保障软件安全?5大安全任务值得考虑
- OpenSSF 安全计划:SBOM 将驱动软件供应链安全
- Use Patroni callback script to bind VIP pit
- C Expert Programming Chapter 4 The Shocking Fact: Arrays and Pointers Are Not the Same 4.3 What is a Declaration and What is a Definition
- C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.2 我的代码为什么无法运行
- 详解八大排序
猜你喜欢
随机推荐
The Road to Ad Monetization for Uni-app Mini Program Apps: Full Screen Video Ads
manipulation of file contents
word 公式编辑器 键入技巧 | 写数学作业必备速查表
[Evaluation model] Topsis method (pros and cons distance method)
你以为border-radius只是圆角吗?【各种角度】
7-3 LVS+Keepalived Cluster Description and Deployment
败给“MySQL”的第60天,我重振旗鼓,四面拿下蚂蚁金服offer
【C语言进阶】程序环境和预处理
leetcode 12. Integer to Roman numeral
字节最爱问的智力题,你会几道?
day13--postman接口测试
Interesting Kotlin 0x0E: DeepRecursiveFunction
The difference between px, em, and rem
Tactile intelligent sharing - SSD20X realizes upgrade display progress bar
5个开源组件管理小技巧
读者让我总结一波 redis 面试题,现在肝出来了
go module的介绍与应用
7-1 LVS+NAT load balancing cluster, NAT mode deployment
Chapter 5 C programming expert thinking 5.4 alert Interpositioning of links
看DevExpress丰富图表样式,如何为基金公司业务创新赋能



![[21 Days Learning Challenge] Image rotation problem (two-dimensional array)](/img/51/fb78f36c71e1eaac665ce9f1ce04ea.png)





