当前位置:网站首页>871.最低加油次数(动态规划)
871.最低加油次数(动态规划)
2022-07-30 05:39:00 【Linke66】

解题思路:
动态规划
dp[i]表示,加油i次最远可以到达的距离;
关键,如果经过j次加油可以到达i这个位置的加油站,那么就可以在这个站加油获得油量,从而更新dp[j+1]
class Solution {
public:
//stations[0]是加油站位置,stations是加油站有多少汽油
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
int n=stations.size();
//dp[i]代表加油i次能够走到的最远距离
//因为一共有n个加油站,因此可以加油n次,包括不加油的0次
vector<long>dp(n+1,0);
dp[0]=startFuel; //一次油不加,一开始有多少油,就走多远
for(int i=0;i<n;++i){
//从第1个(下标为0)的加油站开始
for(int j=i;j>=0;--j){
//如果可以经过j次加油到达i这个加油站,那么就可以在这个站加油获得油量
if(dp[j]>=stations[i][0]){
dp[j+1]=max(dp[j+1],dp[j]+stations[i][1]);
}
}
}
for(int i=0;i<=n;++i){
if(dp[i]>=target)
return i;
}
return -1;
}
};
改变题干:
初始有100单位燃油;
油箱有最大容量100单位燃油;
其他不变;
class Solution {
public:
//stations[0]是加油站位置,stations是加油站有多少汽油
int minRefuelStops(int target,vector<vector<int>>& stations) {
int n=stations.size();
//dp[i]代表加油i次能够走到的最远距离
//因为一共有n个加油站,因此可以加油n次,包括不加油的0次
vector<long>dp(n+1,0);
dp[0]=100; //一次油不加,一开始有100升油,就走多远
for(int i=0;i<n;++i){
//从第1个(下标为0)的加油站开始
for(int j=i;j>=0;--j){
//如果可以经过j次加油到达i这个加油站,那么就可以在这个站加油获得油量
if(dp[j]>=stations[i][0]){
//在该站获得油量以后,最多也只能再往前走100
dp[j+1]=max(dp[j+1],dp[j]+min(100,stations[i][1]));
}
}
}
for(int i=0;i<=n;++i){
if(dp[i]>=target)
return i;
}
return -1;
}
};
边栏推荐
猜你喜欢

MYSQL-InnoDB的线程模型

optimizer.zero_grad()

Solve the problem that the local nacos is not configured but the localhost8848 connection exception always occurs

报错:npm ERR code EPERM

navicat无法连接mysql超详细处理方法

JVM之GC 调优基础知识(一)

More fragrant open source projects than Ruoyi in 2022

个人博客系统(附源码)

postman 请求 post 调用 传 复合 json数据

手把手教你彻底卸载MySQL
随机推荐
4、nerf(pytorch)
postman 请求 post 调用 传 复合 json数据
2022 SQL big factory high-frequency practical interview questions (detailed analysis)
asyncawait和promise的区别
646.最长数对链(动态规划)
微信小程序开发学习
MySQL的 DDL和DML和DQL的基本语法
mysql time field is set to current time by default
数据操作 / 数据预处理
create-nuxt-app创建出来的项目没有server
Basic syntax of MySQL DDL and DML and DQL
Frobenius norm(Frobenius 范数)
cnpm installation steps
flask的笔记
More fragrant open source projects than Ruoyi in 2022
Graphic mirror symmetry (schematic diagram)
JVM之GC 调优工具 Arthas 实战使用(二)
“tensorflow.keras.preprocessing“ has no attribute “image_dataset_from_directory“
Numpy 中 np.vstack() 和 np.hstack() 简单解析
PyCharm usage tutorial (more detailed, picture + text)