您的位置:首页 > 其它

【Leetcode】Jump Game II (DP)

2014-11-10 09:26 369 查看
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.

Your goal is to reach the last index in the minimum number of jumps.

For example:

Given array A = 
[2,3,1,1,4]


The minimum number of jumps to reach the last index is 
2
. (Jump 
1
 step
from index 0 to 1, then 
3
 steps to the last index.)

这道题的思路和I差不多,只是需要维护一个step来记录长度,也就是说只有超过了上次跳跃的最大长度,step才会增加。

代码如下

public static int jump(int[] A) {
if (A == null || A.length == 0)
return 0;
int lastDestination = 0;
int destination = 0;
int step = 0;

for (int i = 0; i <= destination && i < A.length; i++) {
if (i > lastDestination) {
step++;
lastDestination = destination;
}
destination = Math.max(destination, A[i] + i);
}
if (destination < A.length - 1)
return 0;
return step;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: