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.
用动态规划来做,jump[i]表示在i位置剩余的最大步数(注意是剩余最大步数,不包括A[i])。
jump[i] = max{jump[i-1], A[i-1]} - 1.
遇到jump[i]<0就返回false.
另外这里只用到jump[i-1],因此不需要一个额外数组来存储jump,只要一个变量就行了。
public class Solution {
public boolean canJump(int[] A) {
int maxRemain = 0;
for(int i = 1; i < A.length; i++){
maxRemain = Math.max(maxRemain, A[i - 1]) - 1;
if(maxRemain < 0)
return false;
}
return true;
}
}
本文介绍如何通过动态规划解决跳跃游戏问题,利用跳转数组记录剩余步数,最终判断能否到达数组末尾。
5514

被折叠的 条评论
为什么被折叠?



