您的位置:首页 > 其它

#leetcode#Jump Game II

2015-06-14 12:21 316 查看
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.)

看见题目懵了, 完全想不到应该怎么去处理这个最小步数, 不过既然jump game I 用greedy解决了, greedy的过程就保证了走过的步数是最少的, 所以只需要记录一下greedy中走了多少步就可以了。。

在这里看到两种解法http://blog.csdn.net/linhuanmars/article/details/21356187, code ganker大神的只记录 走了 几步, 和下面评论中的 记录走过的路径, 两种解法, 我贴在一起方便复习, 如果侵权立马删除哈

public class Solution {
public int jump(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int lastReach = 0;
int reach = 0;
int steps = 0;
for(int i = 0; i <= reach && i < nums.length; i++){
if(i > lastReach){
steps++;
lastReach = reach;
}

reach = Math.max(reach, nums[i] + i);
}

if(reach < nums.length - 1)
return 0;
return steps;
}
}

记录路径的解法:

public class Solution {
public int jump(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int lastReach = 0;
int reach = 0;
int index = 0;
List<Integer> steps = new ArrayList<>();
for(int i = 0; i < nums.length; i++){
if(i > lastReach){
steps.add(index);
lastReach = reach;
}

if(reach < nums[i] + i){
reach = nums[i] + i;
index = i;
}
}

if(reach < nums.length - 1)
return 0;
return steps.size();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode