# 656. Coin Path

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+1``i+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 = [0, 0, 0], B = 2

``````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;
}
};
``````

``````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;
}
};
``````

House Robber II

House Robber

Frog Jump

Jump Game

Jump Game II

https://discuss.leetcode.com/topic/98399/c-dp-o-nb-time-o-n-space

https://discuss.leetcode.com/topic/98491/java-22-lines-solution-with-proof

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation