Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The integer Bdenotes 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], 2
Output: [1,3,5]

Example 2:

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

Note:

  1. Path Pa1, Pa2, ..., Pan is lexicographically smaller than Pb1, Pb2, ..., Pbm, if and only if at the first i where Pai and Pbi differ, Pai < Pbi; when no such i exists, then n < m.
  2. A1 >= 0. A2, ..., AN (if exist) will in the range of [-1, 100].
  3. Length of A is in the range of [1, 1000].
  4. B is in the range of [1, 100].

给一个数组A,数组元素的值代表cost,一个整数B表示能走的最大步数。从第1个位置开始走,每次能走的步数是B步以内,走到某个位置就要付出该位置的cost,目标是到达最末尾位置,使得付出总cost值最小,输出所有路径。如果某个位置是-1,不可以走这个位置。如果有多个路径,输出按字母顺序排列。

解法:DP, 从后往前跳。首先判断最后一个位置是否为-1,如果是说明无法到达最后位置,返回空。用一个一维数组dp记录跳到i位置所用的最小cost, 从i位置跳时有B种跳法,再去判断每一个跳法的dp值。

dp[i] = A[i] + dp[j]  (dp[j]为从B种跳法中的一种的dp值)

Python:

# Time:  O(n * B)
# Space: O(n)
class Solution(object):
def cheapestJump(self, A, B):
"""
:type A: List[int]
:type B: int
:rtype: List[int]
"""
result = []
if not A or A[-1] == -1:
return result
n = len(A)
dp, next_pos = [float("inf")] * n, [-1] * n
dp[n-1] = A[n-1]
for i in reversed(xrange(n-1)):
if A[i] == -1:
continue
for j in xrange(i+1, min(i+B+1,n)):
if A[i] + dp[j] < dp[i]:
dp[i] = A[i] + dp[j]
next_pos[i] = j
if dp[0] == float("inf"):
return result
k = 0
while k != -1:
result.append(k+1)
k = next_pos[k]
return result  

C++:

class Solution {
public:
vector<int> cheapestJump(vector<int>& A, int B) {
if (A.back() == -1) return {};
int n = A.size();
vector<int> res, dp(n, INT_MAX), pos(n, -1);
dp[n - 1] = A[n - 1];
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;
}
}
}
if (dp[0] == INT_MAX) return res;
for (int cur = 0; cur != -1; cur = pos[cur]) {
res.push_back(cur + 1);
}
return res;
}
};

C++:

class Solution {
public:
vector<int> cheapestJump(vector<int>& A, int B) {
if (A.back() == -1) return {};
int n = A.size();
vector<int> res, dp(n, INT_MAX), pos(n, -1), len(n, 0);
dp[0] = 0;
for (int i = 0; i < n; ++i) {
if (A[i] == -1) continue;
for (int j = max(0, i - B); j < i; ++j) {
if (dp[j] == INT_MAX) continue;
int t = A[i] + dp[j];
if (t < dp[i] || (t == dp[i] && len[i] < len[j] + 1)) {
dp[i] = t;
pos[i] = j;
len[i] = len[j] + 1;
}
}
}
if (dp[n - 1] == INT_MAX) return res;
for (int cur = n - 1; cur != -1; cur = pos[cur]) {
res.insert(res.begin(), cur + 1);
}
return res;
}
};

C++:

class Solution {
public:
vector<int> cheapestJump(vector<int>& A, int B) {
vector<int> result;
if (A.empty() || A.back() == -1) {
return result;
}
const int n = A.size();
vector<int> dp(n, numeric_limits<int>::max()), next(n, -1);
dp[n - 1] = A[n - 1];
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] == numeric_limits<int>::max()) {
continue;
}
if (A[i] + dp[j] < dp[i]) {
dp[i] = A[i] + dp[j];
next[i] = j;
}
}
}
if (dp[0] == numeric_limits<int>::max()) {
return result;
}
int k = 0;
while (k != -1) {
result.emplace_back(k + 1);
k = next[k];
}
return result;
}
};

  

  

类似题目:

[LeetCode] 198. House Robber 打家劫舍

[LeetCode] 213. House Robber II 打家劫舍 II

[LeetCode] 55. Jump Game 跳跃游戏

[LeetCode] 45. Jump Game II 跳跃游戏 II

[LeetCode] 403. Frog Jump 青蛙跳

All LeetCode Questions List 题目汇总

[LeetCode] 656. Coin Path 硬币路径的更多相关文章

  1. [LeetCode] Coin Path 硬币路径

    Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The ...

  2. leetcode 656. Coin Path

    Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The ...

  3. [LeetCode] 322. Coin Change 硬币找零

    You are given coins of different denominations and a total amount of money amount. Write a function ...

  4. [LeetCode] 71. Simplify Path 简化路径

    Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", ...

  5. LC 656. Coin Path 【lock, Hard】

    Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The ...

  6. [LeetCode] 518. Coin Change 2 硬币找零 2

    You are given coins of different denominations and a total amount of money. Write a function to comp ...

  7. 【一天一道LeetCode】#113. Path Sum II

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  8. [LeetCode] 62. Unique Paths 唯一路径

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The ...

  9. 【LeetCode】113. Path Sum II 解题报告(Python)

    [LeetCode]113. Path Sum II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fu ...

随机推荐

  1. ajax、axios、fetch 对比

    前言 今天在看到一个比较好的插件,写一个示例时,由于需要请求在线数据,官方给的是用 $.get(),就为了一个示例使用 JQuery 没必要. 又找了找,发现有用 fecth 的,挺方便,这里就做一个 ...

  2. Thinkphp下记录和统计时间(微秒)和内存使用情况

    * 记录和统计时间(微秒)和内存使用情况 * 使用方法: * <code> * G('begin'); // 记录开始标记位 * // ... 区间运行代码 * G('end'); // ...

  3. PC端自适应布局

    截止目前,国内绝大多数内容为主的网站(知乎,果壳,V2EX,网易新闻等)均使用内容区定宽布局,大多数电商网站(网易考拉,京东,聚美优品)也使用了内容区定宽的布局,也有些网站使用了自适应布局: 天猫 内 ...

  4. 51Node1228序列求和 ——自然数幂和模板&&伯努利数

    伯努利数法 伯努利数原本就是处理等幂和的问题,可以推出 $$ \sum_{i=1}^{n}i^k={1\over{k+1}}\sum_{i=1}^{k+1}C_{k+1}^i*B_{k+1-i}*(n ...

  5. BM递推杜教版【扩展】

    也就是模数不是质数的时候, //下面的板子能求质数和非质数,只需要传不同的参数. #include <cstdio> #include <cstdlib> #include & ...

  6. 浅谈H5图片中object-fit的属性及含义/ 小程序image mode属性中scaleToFill,aspectFit,widthFix等类似

    我们在H5中对于图片的属性包含如下: object-fit属性有哪些值呢? object-fit: fill;  object-fit: contain;  object-fit: cover;  o ...

  7. Centos 不重启 修改ulimit参数

    1. 查看limits.conf文件 cat /etc/security/limits.conf 2. 打开编辑limits.conf文件 sudo vim /etc/security/limits. ...

  8. P4279 【[SHOI2008]小约翰的游戏】

    我怎么什么都不会啊\(QAQ\)博弈论怎么和期望一样玄学啊\(QAQ\) 我们分几种情况讨论: \(Case1\):只有一堆且为1,那么后手胜利 \(Case2\):每一堆都是1,那么只需要判断奇偶性 ...

  9. Pandas的基本用法

    Pandas是使用python进行数据分析不可或缺的第三方库.我们已经知道,NumPy的ndarray数据结构能够很好地进行数组运算,但是当我们需要进行为数据添加标签,处理缺失值,对数据分组,创建透视 ...

  10. linux命令之------Chown命令

    Chown命令 1) 作用:将指定文件的拥有者改为指定的用户或组. 2) -c:显示更改的部分的信息. 3)-f:忽略错误信息. 4)-h:修复符号链接. 5)-v:显示详细的处理信息. 6)-R:处 ...