首页 > 代码库 > 【LeetCode】Jump Game II
【LeetCode】Jump Game II
Jump Game II
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数组,将数组A从后往前遍历,jump[i]存储第[i]个元素到A[n-1]的最小jump数。
因此jump[i-1]就是A[i-1]jump范围内最小jump值+1.可惜TLE了。
最优美的解法与Jump Game类似,从前往后遍历一次,记录几个关键点就够了:
jump:目前为止的jump数
lastMax:从A[0]进行jump次jump之后达到的最大范围
curMax:从0~i这i+1个A元素中能达到的最大范围
当lastMax<i,说明jump次已经不足以覆盖当前第i个元素,因此需要增加一次jump,使之达到
记录的curMax。
class Solution { public: int jump(int A[], int n) { int jump = 0; int lastMax = 0; //trace the max with jump times jump int curMax = 0; //trace the max from 0~i for(int i = 0; i < n; i ++) { if(lastMax < i) { jump ++; // need a jump! lastMax = curMax; // jump to new max(curMax) } curMax = max(curMax, A[i]+i); } return jump; } };