题目描述:
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.)
这个方法的关键就是如何在不回溯的情况下找到最大值并继续下一次查找。想通了以后实际上很简单。我们用curr来记录已经找到的可以跳到的最大距离,即curr=i + A[i],i是当前位置即已经走过的距离,A[i]则是可以跳过的距离。用len来记录前一次跳跃所能达到的最大长度,这样当i>len时即标志着进入了新的搜索范围,此时res++,len=curr。
代码如下:
class Solution {
public:
int jump(int A[], int n) {
int res(0), len(0), curr(0);
for (int i = 0; i < n; i++){
if (i>len){
len = curr;
res++;
}
curr = max(curr, i + A[i]);
}
return res;
}
};