[LeetCode] Jump Game II

来源:互联网 发布:网页美工设计视频 编辑:程序博客网 时间:2024/06/06 18:08
[Problem]

Given an array of non-negative integers, you are initiallypositioned at the first index of the array.

Each element in the array represents your maximum jump length atthat position.

Your goal is to reach the last index in the minimum number ofjumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is2. (Jump 1 step from index 0 to 1, then3 steps to the last index.)


[Analysis]
与Jump Game类似,使用intdp[1:n]数组,dp[i]表示从A[i]跳到A[n]需要的步数,从n-1~1更新数组。
对于dp[i],令step =1至A[i],若dp[i+step]>0,如果dp[i]==0,则dp[i]=dp[i+step]+1,否则dp[i]=dp[i]< dp[i+step]+1 ? dp[i] :dp[i+step]+1。

step可以从1~A[i]按step++的方式递增,但是这样在Large Judge时会TLE,更好的方法是:
(1)如果dp[i+step]=0,即从i跳一个长度为step的一跳后,仍然无法从A[i+step]跳到A[n],那么直接从A[i+step]能够到达最远的地方的后面一位开始跳,即step+= A[i+step] + 1。
(2)如果dp[i+step]>0,即从i跳一个长度为step的一跳后,可以从A[i+step]跳到A[n],用first[i+step]记录从A[i+step]跳到A[n]使用最少跳动次数时,需要先跳到的地方,那么直接将step更新为first[i+step]-i。

[Solution]

class Solution {
public:
int jump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// empty
if(n <= 0)return true;

// non-empty
int mark[n], first[n];
memset(mark, 0, sizeof(mark));
mark[n-1] = 0;

// dynamic search
for(int i = n-2; i >= 0; --i){

// jump step = 1:A[i]
int j = 1;
while(j <= A[i]){
// jump in one step
if(i + j == n - 1){
mark[i] = 1;
first[i] = n - 1;
break;
}
// end of search
else if(i + j > n - 1){
break;
}
// jump a j-length step
else{
// can reach A[n] by A[i+j]
if(mark[i+j] > 0){
// has never been to A[n] from A[i]
if(mark[i] == 0){
mark[i] = mark[i+j] + 1;
first[i] = i+j;
}
// has already been to A[n] from A[i], update the min jumps
else{
if(mark[i+j] + 1 < mark[i]){
mark[i] = mark[i+j] + 1;
first[i] = i+j;
}
}
j = first[i+j] - i;
}
else{
j += A[i+j] + 1;
}
}
}
}

return mark[0];
}
};


说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击