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.)
超时代码为:
int jump(int A[], int n) {
if(A==NULL || n<2){
return 0;
}
if(n == 2 || A[0] >= n-1)
{
return 1;
}
int* minStepList=new int[n];;
for(int i=0; i<n; ++i)
{
minStepList[i]=0xffff;
}
minStepList[n-1]=0;
minStepList[n-2]=1;
int stepTmp=0;
for(int j=n-3; j>=0; --j)
{
for(int i=A[j]; i>0; --i)
{
if(A[j] >= n-1-j)
{
minStepList[j]=1;
break;
}
if(i+j < n)
{
stepTmp=1+minStepList[i+j];
if(stepTmp < minStepList[j])
{
minStepList[j]=stepTmp;
}
}
else
{
break;
}
}
}
return minStepList[0];
}
后参考别人代码,思路为用一个数组保存第1个结点到第i个结点的最小跳数,该数组为一个递增数组。代码为:
class Solution {
public:
int* dp;
int jump(int A[], int n) {
if(n==0)
{
return INT_MAX;
}
dp = new int[n];
dp[0] = 0;
for(int i=1;i<n;i++)
{
dp[i] = INT_MAX;
}
for(int i=1;i<n;i++)
{
for(int j=0;j<i;j++)
{
if(j+A[j]>=i)
{
int tmp = dp[j]+1;
if(tmp < dp[i])
{
dp[i] = tmp//遇到的第一个j结点能够一步跳到i结点的则为最短的
break;
}
}
}
}
return dp[n-1];
}
};