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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
array A
length n
Analysis:
1.do directly. If A[i]is 0 and A[i]+i is not equal to n -1, then go to check A[i-1] else; go to A[i] + i.
if A[i]+i >= n-1 return true,
if i == 0 return false.
e.g. A = [3,2,1,0,4]
init: i = 0, A[i] = 3
i = 3, A[i] = 0
i = 2, A[i] = 1
i = 3 A[i] = 0
i = 2.......this go to a loop without exit loop.
so we need to add status for each i to record whether it can be choosed.
bool canJump(int A[], int n) {
if(n<1)
return false;
if(n == 1)
return true;
int cur = 0;
int step = 0;
while(A[0] > 0 && cur < (n-1))
{
if (A[cur] == 0)
{
cur--;
if (A[cur])
{
A[cur]--;
}
}
else
{
step = A[cur];
cur += step;;
}
}
if (cur >= (n-1))
{
return true;
}
return false;
}
The script above set array A itself as the status array. When we find node i can't be choosed, set A[i] = 0;
This script can return correct answer, but receive RUNTIME ERROR with a long input.
2. Futher
Why the script above receive RUNTIME ERROR? It waste too much time to roll back and compare.
Reread the description, it is obvious that when (A[i] + i) is not smaller then n - 1, it will should return true. Then how can we get to node i? Node i can be choosed only when the max(A[j] + j) (j< i)is not smaller then i.
For each node i, the max step we can jump to is only related with A[i] and i.
Yeah, we can transfer this into a DP problem to find the max(A[i] + i) with conditionmax(A[j] + j) >= i (j< i)for each i
transfer equation: status[i] = max(status[i-1],A[i] + i)
status[0] = A[0]
bool canJump(int A[], int n)
{
int* status = new int[n];
status[0] = A[0];
if(status[0]==0 && n>1)
{
return false;
}
for(int i=1;i<n;i++)
{
status[i] = std::max(status[i-1],A[i] + i);
//can not reach the next node
if( status[i]<=i && i!=n-1 )
{
delete[] status;
return false;
}
// this has satisfy the condition.
if (status[i] >= (n - 1))
{
break;
}
}
delete[] status;
return true;
}
referred to http://blog.csdn.net/worldwindjp/article/details/18990777