class Solution {
public:
int jump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int *dist = new int[n+1];
dist[n - 1] = 0;
int *next = new int[n+1];
next[n - 1] = n - 1;
int pos = n -1;
int mindist = 0;
A[n-1] = 0;
for(int i = n -2; i >= 0; i--){
if(A[i] == 0){
next[i] = -1;
dist[i] = -1;
continue;
}
if(i + A[i] >= n -1){
dist[i] = 1;
next[i] = n - 1;
continue;
}
if(A[i] <= A[i+1] + 1){
if(i + A[i] >= next[i + 1] && next[i+1] >= 0){
dist[i] = 1 + dist[next[i + 1]];
next[i] = next[i + 1];
} else {
pos = i;
dist[pos] = -1;
for(int k = 1; k <= A[i]; k++){
if(dist[i + k] > 0){
if(dist[pos] < 0){
dist[pos] = dist[i + k];
pos = i + k;
} else {
if(dist[i + k] < dist[pos]){
pos = i+ k;
}
}
}
}
if(dist[pos] >= 0){
dist[i] = 1 + dist[pos];
next[i] = pos;
} else {
dist[i] = -1;
next[i] = -1;
}
}
} else {
pos = i;
dist[pos] = -1;
for(int k = 1; k <= A[i]; k++){
if(dist[i + k] > 0){
if(dist[pos] < 0){
dist[pos] = dist[i + k];
pos = i + k;
} else {
if(dist[i + k] < dist[pos]){
pos = i+ k;
}
}
}
}
if(dist[pos] >= 0){
dist[i] = 1 + dist[pos];
next[i] = pos;
} else {
dist[i] = -1;
next[i] = -1;
}
}
}
return dist[0];
}
};
Jump Game II
最新推荐文章于 2022-07-13 20:43:33 发布