Jump Game II
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.)
动态规划:自底向上求,每跳一步,最远能跳多少。 注意每一次之间分界点的选择:排除了那些一定不可能的点。
class Solution {
public:
int jump(int A[], int n)
{
if(NULL == A || n <= 1)
return 0;
int steps = 0;
int idx = 0;
while(idx < n)
{
if(A[idx] > 0)
++steps;
else
return 0;
int rightmost = A[idx] + idx;
if(rightmost >= n - 1)
return steps;
int temp = 0;
for(int j = idx + 1; j <= rightmost; ++j)
if(A[j] + j >= temp)
{
temp = A[j] + j;
idx = j;
}
}
return steps;
}
};