题目一: 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.)
思路: 解法有二,一种是递归,暴力法破解。一种是计算每步能跳的最远距离。
解法一: 暴力法
class Solution {
public:
int jump(vector<int>& nums) {
vector<int> result;
nextjump(nums,result,0,0);
sort(result.begin(),result.end());
return result[0];
}
void nextjump(vector<int>& nums,vector<int>& result,int pos,int jump)
{
if(pos>=nums.size()-1)
{
result.push_back(jump);
return;
}
for(int i=1;i<=nums[pos];++i)
{
nextjump(nums,result,pos+i,jump+1);
}
}
};
运行结果: 比较短的测试用例可以通过
但是提交到leetcode是TLE
看到最后一个测试用例很长,然后单独测试一下。
结果是栈溢出,也不奇怪了。
解法二: 参考了左程云的书籍
class Solution {
public:
int jump(vector<int>& nums) {
int jump=0,cur=0,next=0;
for(int i=0;i<nums.size();++i){
if(cur<i){
jump++;
cur=next;
}
next=max(next,i+nums[i]);
}
return jump;
}
};
测试结果: 只击败了17%的代码,好忧桑。
题目二: 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.
思路: 在一题的基础上修改,若走到某个位置发现之前的所有跳跃点都跳不到该位置则返回false。
class Solution {
public:
bool canJump(vector<int>& nums) {
int cur=0,next=0,i;
for( i=0;i<nums.size();++i){
if(cur<i){
cur=next;
if(next<i)
return false;
}
next=max(next,i+nums[i]);
}
return true;
}
};