Description
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.
分析一
题目的意思是:给你一个数组,数组的值代表能够跳跃的最大范围,现在问能否从开始跳到数组末尾。
- 动态规划的解法,dp[i]表示到达i时剩余的步数,当前位置的剩余步数和当前位置的跳力较大的那个数决定了当前能到的最远距离。而下一个位置的剩余步数就等于较大值减去1,因为需要花费一个跳力到达下一个位置。状态转移方程为:
dp[i]=max(dp[i-1],nums[i-1])-1;
代码一
class Solution {
public:
bool canJump(vector<int>& nums) {
vector<int> dp(nums.size(),0);
dp[0]=nums[0];
for(int i=1;i<nums.size();i++){
dp[i]=max(dp[i-1],nums[i-1])-1;
if(dp[i]<0){
return false;
}
}
return dp[nums.size()-1]>=0;
}
};
分析二
- 见代码注释
代码二
class Solution {
public:
bool canJump(int A[], int n) {
int max_val=0; //max_val标记能跳到的最远处。
for(int i=0;i<n&&i<=max_val;i++){ //max_val>=i表示此时能跳到i处,0<=i<n表
max_val=max(max_val,A[i]+i); //示扫描所有能到达的点,在改点处能跳到的最远处。
}
if(max_val<n-1){ //如果最后跳的最远的结果大于等于n-1,那么满足,能跳到最后,否则,不能。
return false;
}
return true;
}
};
Python 代码 贪心实现
cur_reach表示从当前位置还能走的最大步数,初始化为1,每遍历一次,要减去1,通过nums的位置的最大步数来更新cur_reach的最大步数。
class Solution:
def canJump(self, nums: List[int]) -> bool:
cur_reach=1
for i in range(len(nums)):
cur_reach-=1
if cur_reach<0:
return False
else:
cur_reach=max(cur_reach,nums[i])
return True
Python DP实现
这里递推公式很好写,要注意一些corner case, 比如[2,0], [2,0,0]这种情况是可以pass的。
class Solution:
def canJump(self, nums: List[int]) -> bool:
# dp[i]=max(dp[i-1],nums[i-1])-1
# dp[0]=nums[0]
n = len(nums)
dp = [0]*(n)
dp[0]=nums[0]
for i in range(1,n):
dp[i]=max(dp[i-1],nums[i-1])-1
if dp[i]<0:
return False
return dp[n-1]>=0