博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
656. Coin Path
阅读量:7191 次
发布时间:2019-06-29

本文共 1897 字,大约阅读时间需要 6 分钟。

Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The integer B denotes that from any place (suppose the index is i) in the array A, you can jump to any one of the place in the array A indexed i+1i+2, …, i+B if this place can be jumped to. Also, if you step on the index i, you have to pay Ai coins. If Ai is -1, it means you can’t jump to the place indexed i in the array.

Now, you start from the place indexed 1 in the array A, and your aim is to reach the place indexed N using the minimum coins. You need to return the path of indexes (starting from 1 to N) in the array you should take to get to the place indexed N using minimum coins.

If there are multiple paths with the same cost, return the lexicographically smallest such path.

If it's not possible to reach the place indexed N then you need to return an empty array.

Example 1:

Input: [1,2,4,-1,2], 2Output: [1,3,5]

 

Example 2:

Input: [1,2,4,-1,2], 1Output: []
class Solution {public:    vector
cheapestJump(vector
& A, int B) { vector
ans; if (A.empty() || A.back() == -1) return ans; int n = A.size(); vector
dp(n, INT_MAX), pos(n, -1); dp[n-1] = A[n-1]; // working backward for (int i = n-2; i >= 0; i--) { if (A[i] == -1) continue; for (int j = i+1; j <= min(i+B, n-1); j++) { if (dp[j] == INT_MAX) continue; if (A[i]+dp[j] < dp[i]) { dp[i] = A[i]+dp[j]; pos[i] = j; } } } // cannot jump to An if (dp[0] == INT_MAX) return ans; int k = 0; while (k != -1) { ans.push_back(k+1); k = pos[k]; } return ans; }};

 

 

转载于:https://www.cnblogs.com/jxr041100/p/7889133.html

你可能感兴趣的文章
【转】IntelliJ IDEA2016.1 + maven 创建java web 项目
查看>>
微软宣布支持基于虚拟机的Azure IOT Edge服务
查看>>
51信用卡 Android自动埋点实践
查看>>
以Chef和Ansible为例快速入门服务器配置
查看>>
以流动债务为例论指标的合理使用
查看>>
保Cloudera弃Hortonworks,新平台将支持五大云供应商
查看>>
Golang 入门系列(九) 如何读取YAML,JSON,INI等配置文件
查看>>
MPAndroidChart 教程:设置颜色 Setting Colors
查看>>
一文教会你数据库性能调优(附某大型医院真实案例)
查看>>
在 kubectl 中使用 Service Account Token
查看>>
松禾资本厉伟:创新的思考
查看>>
ajax跨域请求数据
查看>>
Linux 查找大文件
查看>>
SSM-Spring-13:Spring中RegexpMethodPointcutAdvisor正则方法切入点顾问
查看>>
Android - 关于设备版本号
查看>>
听说你Binder机制学的不错,来面试下这几个问题(一)
查看>>
PostgreSQL, SQL Server 逻辑增量 (通过逻辑标记update,delete) 同步到 Greenplum, PostgreSQL...
查看>>
linux中btt工具详解
查看>>
开源监控利器Prometheus初探
查看>>
前端测试:Part II (单元测试)
查看>>