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.)
Note:
You can assume that you can always reach the last index.
思路一:动态规划,91/92 passed,超时
class Solution {
public:
int jump(vector<int>& nums)
{
int len = nums.size();
int dp[1000000] = {};
dp[0] = 0;
for(int i=1;i<len;i++)
dp[i] = 999999;
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len && j<=i+nums[i];j++)
{
dp[j] = min(dp[j],dp[i]+1);
}
}
return dp[len-1];
}
};
思路二:BFS,改进后45ms AC
class Solution {
public:
int _visit[1000000];
struct cxk
{
int _index;
int step;
cxk(int a,int b)
{
_index = a;
step = b;
}
};
int jump(vector<int>& nums)
{
int len = nums.size();
queue<cxk> q;
q.push(cxk(0,1));
_visit[0] = 1;
int it_max = 1; //当前开始遍历的下标首地址
while(!q.empty())
{
cxk tmp = q.front();
q.pop();
if(tmp._index == len-1) //已经走到最后一步
{
return tmp.step-1;
}
for(int i=it_max;i<len && i<=tmp._index+nums[tmp._index];i++)
{
if(_visit[i] == 0)
{
q.push(cxk(i,tmp.step+1));
_visit[i] = 1;
}
}
it_max = tmp._index+nums[tmp._index]+1; //已经找过的下标就不用再找了
}
return -1;
}
};
思路三:类似BFS,不用queue就能实现,直接模拟
19ms AC
class Solution {
public:
int jump(vector<int>& nums)
{
int n = nums.size(), step = 0, start = 0, end = 0;
while (end < n - 1)
{
step++;
int maxend = end + 1;
for (int i = start; i <= end; i++) {
if (i + nums[i] >= n - 1)
return step;
maxend = max(maxend, i + nums[i]);
}
start = end + 1;
end = maxend;
}
return step;
}
};