题目描述:
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
Accepted C++ Solution:
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if(n < 2) return 0;
int level = 0, currentMax = 0,i = 0, nextMax = 0;
while(currentMax-i+1 > 0) {
level++;
for(; i <= currentMax; i++) { //遍历每一层,更新下一层能到到达的最后位置
nextMax = max(nextMax,nums[i]+i);
if(nextMax >= n-1) return level; //如果能到达的节点超过边界,则返回层
}
currentMax = nextMax;
}
return 0;
}
};
把此问题转化为BFS问题,其中级别i中的节点是在第i-1次跳转中可以到达的所有节点。例如 2 3 1 1 4 分层为:
2 ||
3 1 ||
1 4 ||
显然,4的最小跳跃是2,因为4是3级。