題目:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2
. (Jump 1
step
from index 0 to 1, then 3
steps to the last index.)
解題:
基本和ump Game相同,需要中間處理一下,比如數據 3 2 1,後面2 1就沒有用,不用遍歷這些數據
代碼:
class Solution {
public:
int jump(int A[], int n) {
bool mark[n];
memset(mark, 0, sizeof(mark));
int mx = -1;
for(int i = 0; i < n; i ++) {
if(A[i] <= mx) {
mark[i] = 1;
}
mx = max(mx, A[i]);
mx --;
}
int f[n];
for(int i = 0; i < n; i ++)
f[i] = INF;
f[0] = 0;
for(int i = 0; i < n; i ++) {
if(mark[i]) continue;
for(int j = 1; j <= A[i] && i + j < n; j ++) {
if(mark[i + j] && i + j != n - 1) continue;
f[i + j] = min(f[i + j], f[i] + 1);
}
}
return f[n - 1];
}
private:
static const int INF = 1 << 30;
};