Jump Game
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.
解析
每一个数组的数组表示能跳的最大步数,判断能否从数组开始位置跳到末尾。
解法1:回溯
判断每个位置能否达到最末尾,如果能返回true,从每个位置的步数从大到小递归。
但是会超时。
class Solution {
public:
bool canJump(vector<int>& nums) {
return jump(nums, 0);
}
bool jump(vector<int>& nums, int i){
if(i >= nums.size()-1)
return true;
for(int j = nums[i];j >= 1;j--){
if(jump(nums, i+j))
return true;
}
return false;
}
};
解法2:动态规划
用一个数组dp表示跳到当前位置时,剩余的步数。当前位置的跳力和当前位置剩余步数的最大值决定了能跳的最远距离,所以下一位置的剩余步数为上一位置的最大距离-1;当有剩余步数小于0时,就返回false。
class Solution {
public:
bool canJump(vector<int>& nums) {
int size = nums.size();
vector<int> dp(size, 0);
for(int i=1;i<size;i++){
dp[i] = max(dp[i-1], nums[i-1]) - 1;
if(dp[i]<0)
return false;
}
return true;
}
};
解法3:贪心
维护一个last表示能到末尾的位置,从后往前遍历,如果当前值和下标之和大于等于last,last更新为i。
class Solution {
public:
bool canJump(vector<int>& nums) {
int last = nums.size()-1;
for(int i=nums.size()-1;i>=0;i--){
if(i+nums[i] >= last)
last = i;
}
return last == 0;
}
};
参考
http://www.cnblogs.com/grandyang/p/4371526.html
https://leetcode.com/problems/jump-game/solution/