题目:
45. 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.)
Note:
You can assume that you can always reach the last index.
代码:
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if (n < 2) {
return 0;
}
int level = 0, currentMax = 0, nextMax = 0;
int i = 0;
while(i <= currentMax) {
level++;
for(; i <= currentMax; i++) { // 确定步长(下一步落点)
nextMax = max(nums[i] + i, nextMax);
if(nextMax >= n - 1) {
return level;
}
}
currentMax = nextMax;
}
return 0;
}
};
算法:
要得到到达最终状态的最短步数,基本思路是判断什么时候需要迈步(即步数level++),以及每一步迈出多大长度。当前节点的下标大于上次迈步落点(即currentMax)时,需要进行迈步;而步长由上次迈步到这次迈步中所有节点可达的最远距离觉得。通过动态规划将当前位置所能到达的最远距离和该节点之前所有点获取的最远距离作比较,取max值获得。循环至max值大于最终状态下标说明可达,返回当前level(即步数),不可达则return 0