Difficulty: 3
Frequency: 2
Problem:
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
.
Solution:
The first solution came to me was DFS. It can pass small data test but failed to pass large data test because of Time Limit Exceeded.
The following code was DFS.
class Solution {
public:
bool canJump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n<=1)
return true;
char * c_visited = new char[n];
memset(c_visited, 0, n*sizeof(char));
if (DFS(A, n, c_visited, 0))
{
delete [] c_visited;
return true;
}
else
{
delete [] c_visited;
return false;
}
}
bool DFS(int A[], int n, char * c_visited, int i_visit)
{
c_visited[i_visit] = 1;
for (int i = A[i_visit]; i>=1; i--)
{
int i_new_visit = i_visit + i;
if (i_new_visit>=n-1)
return true;
if (c_visited[i_new_visit])
continue;
if (DFS(A, n, c_visited, i_new_visit))
return true;
}
return false;
}
};
After consulting others' algorithms. I wrote the following code which pass all tests, both small and large.
class Solution {
public:
bool canJump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n==1)
return true;
int i_current_max = A[0]<n-1?A[0]:n-1;
int i_last_max = 0;
int i_temp_max = i_current_max;
do{
for (int i = i_last_max; i<=i_current_max; i++)
{
i_temp_max = i_temp_max>i+A[i]?i_temp_max:i+A[i];
}
if (i_temp_max>=n-1)
return true;
i_last_max = i_current_max;
i_current_max = i_temp_max;
}while(i_current_max>i_last_max);
return false;
}
};
Notes:
Recently, I've written lots of code using DFS. So DFS always came to my mind as the first choice. But sometimes, it is not efficient at all. I need to escape from this think mode.
Someone mentioned DP can solve this problem. I've thought about it, but didn't write any code. I will try DP someday.