题目描述:
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4] 输出: true 解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4] 输出: false 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
AC C++ Solution:
方法1:
class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
if(n < 2) return true;
int i = 0, currentMax = 0, nextMax = 0;
while(currentMax-i+1 > 0) {
for(; i <= currentMax; i++) {
nextMax = max(nextMax, nums[i]+i); //判断下一层能到达的最远距离
if(nextMax >= n-1) return true;
}
if(nextMax == currentMax) //若下一层到达的最远位置和当前最远位置一样,则说明一直原地TP,不可能到达末尾。
return false;
currentMax = nextMax;
}
}
};
方法2:(DP)
class Solution {
public:
bool canJump(vector<int>& nums) {
vector<int> res;
res.push_back(nums[0]);
for(int i=1;i<nums.size();i++){
if(res[i-1]>=i)
res.push_back(max(nums[i]+i,res[i-1])); //把能到达的位置加入到res末尾。
else
res.push_back(0);
}
return res[res.size()-1]>=nums.size()-1; //判断最后到达的位置是否比向量的最后位置大
}
};