当前位置:网站首页>力扣: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]);
}
};
边栏推荐
- How to open a CITIC Securities online account?is it safe?
- Gartner 权威预测未来4年网络安全的8大发展趋势
- C Expert Programming Chapter 5 Thinking about Linking 5.1 Libraries, Linking and Loading
- 8大软件供应链攻击事件概述
- Performance testing with Loadrunner
- What are the steps for how to develop a mall system APP?
- C Expert Programming Chapter 5 Thinking about Chaining 5.6 Take it easy --- see who's talking: take the Turning quiz
- [SemiDrive source code analysis] [MailBox inter-core communication] 47 - Analysis of RPMSG_IPCC_RPC mode limit size of single transmission and limit bandwidth test
- 基于gRPC编写golang简单C2远控
- 【C语言进阶】程序环境和预处理
猜你喜欢

数的划分之动态规划

leetcode 12. Integer to Roman numeral

结构体指针知识要点总结

10 Convolutional Neural Networks for Deep Learning 3

There is an 8 hour difference between the docker installation of mysql and the host.

某母婴小程序加密参数解密
![[Evaluation model] Topsis method (pros and cons distance method)](/img/e7/c24241faced567f3e93f6ff3f20074.png)
[Evaluation model] Topsis method (pros and cons distance method)

word 公式编辑器 键入技巧 | 写数学作业必备速查表

在被面试官说了无数次后,终于潜下心来整理了一下JVM的类加载器

ADC噪声全面分析 -03- 利用噪声分析进行实际设计
随机推荐
day13--postman interface test
数的划分之动态规划
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.1 Arrays are not pointers
Towards Real-Time Multi-Object Tracking(JDE)
读者让我总结一波 redis 面试题,现在肝出来了
C Expert Programming Chapter 5 Thinking about Chaining 5.6 Take it easy --- see who's talking: take the Turning quiz
How to simplify the automation of modern e-procurement?
商城App开发都有哪些功能呢
centos 安装postgresql13 指定版本
7-1 LVS+NAT load balancing cluster, NAT mode deployment
ADC噪声全面分析 -03- 利用噪声分析进行实际设计
Resolved error: npm WARN config global `--global`, `--local` are deprecated
离线采集怎么看sql执行计划
manipulation of file contents
Get the selected content of the radio box
For Qixi Festival, I made a confession envelope with code
在被面试官说了无数次后,终于潜下心来整理了一下JVM的类加载器
Do you think border-radius is just rounded corners?【Various angles】
[One step in place] Jenkins installation, deployment, startup (complete tutorial)
Plus版SBOM:流水线物料清单PBOM