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.)
DP 超时。
class Solution {
public:
int jump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n==0) return 0;
vector<int> minStep(n,-1);
minStep[n-1] = 0;
if(n==1) return 0;
//minStep[n-2] = A[n-2]==0?-1:1;
//if(n==2) return minStep[0];
for(int i = n-2;i>=0;i--)
{
if(A[i]>=n-i)
{
minStep[i] = 1;
}
else
{
for(int j=1;j<=A[i]&&i+j<=n-1;j++)
{
if(minStep[i+j]!=-1)
{
if(minStep[i]==-1) minStep[i] = minStep[i+j]+1;
else minStep[i] = min(minStep[i+j]+1,minStep[i]);
}
}
}
}
return minStep[0];
}
};
贪心算法:从第一个数开始,从它的所有可能性中选择可以跳的最远的那个点,跳到那个点,继续上述过程。
class Solution {
public:
int jump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n==1) return 0;
int i = 0;
int jumps = 0;
int curFar = 0;//How far can we reach currently?
while(i<n)
{
curFar = i + A[i];
jumps ++;
if(currentFar>=n-1) return jumps;
int tempFar = 0;
for(int j=i+1;j<=currentFar;j++)
{
if(j+A[j]>tempFar)
{
tempFar = j+A[j];
i = j;
}
}
}
return jumps;
}
};