题目
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.)
从前往后遍历,纪录每增加一步所能达到的最大距离,有点像BFS中纪录层次的感觉。
代码
public class JumpGameII { public int jump(int[] A) { int minStep = 0; int nextLevel = 0; int curLevel = 0; int N = A.length; for (int i = 0; i < N - 1; ++i) { if (i > curLevel) { curLevel = nextLevel; ++minStep; } if (i + A[i] >= N - 1) { ++minStep; break; } else if (i + A[i] > nextLevel) { nextLevel = i + A[i]; } } return minStep; } }
LeetCode | Jump Game II,布布扣,bubuko.com
原文:http://blog.csdn.net/perfect8886/article/details/21861157