题目描述
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.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
分析
- 方法一:通过循环的方法,从终点开始,记录可以到达终点的最前一个点,如果与出发点相同,则可以到达终点,否则不可到达。
- 方法二:对方法一进行优化,只对 nusm[i] == 0 的情况进行处理,(若 nums[i] != 0 则说明可以到达点),当 nusm[i] == 0 时,进行判断前方的点是否可以跳过这的点达到下一个点,可以比方法一少计算一些,加快了计算速度。
例如:nums = [4,3,2,1,0,1] -------- nums[4]不可以跳过
nums = [4,3,2,2,0,1] -------- nums[4]可以跳过 - 方法三:通过递归的方法,使用贪心策略,加快计算速度。
最终结果
方法一:
class Solution {
public:
bool canJump(vector<int>& nums) {
int des = nums.size()-1, len = nums.size();
for (int i = len-1; i >= 0 ; i--) {
if (i + nums[i] >= des) {
if (i < des) des = i;
}
}
return des == 0;
}
};
方法二:
class Solution {
public:
bool canJump(vector<int>& nums) {
int len = nums.size();
bool flag = true;
for (int i = len-2; i >= 0 ; i--) {
if (nums[i] == 0) {
flag = false;
for (int j = i-1; j >= 0 ;j--) {
if (j + nums[j] > i) {
flag = true;
break;
}
}
if (flag == false)
return false;
}
}
return flag;
}
};
方法三:
class Solution {
public:
bool canJump(vector<int>& nums) {
int len = nums.size();
bool* dp = new bool[len];
memset(dp, false, len);
return jump(nums, len - 1, dp);
}
bool jump(vector<int>& nums, int n, bool* dp) {
if (n == 0) {
if (dp[n] == false)
dp[n] = true;
return dp[n];
}
for (int i = n - 1; i >= 0; i--) {
if (i + nums[i] >= n) {
if (dp[i] == false)
dp[i] = jump(nums, i, dp);
return dp[i];
}
}
return dp[n];
}
};