forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 15
/
coin-path.cpp
38 lines (37 loc) · 1.01 KB
/
coin-path.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Time: O(n * B)
// Space: O(n)
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;
}
};