文章目录
- 1. 题目
- 2. 解题
- 2.1 贪心
- 2.2 BFS
1. 题目
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置假设你总是可以到达数组的最后一个位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
类似题目 LeetCode 55 跳跃游戏
2. 解题
相关题目:
LeetCode 55. 跳跃游戏(贪心)
LeetCode 1306. 跳跃游戏 III(广度优先搜索BFS)
LeetCode 1345. 跳跃游戏 IV(BFS)
LeetCode 1340. 跳跃游戏 V(DP)
LeetCode LCP 09. 最小跳跃次数
2.1 贪心
- 当前可达的最远下标设一个标记 reach
- 在到达 reach 的过程中,不断更新 maxs(可到达的最远下标)
- 当到达 reach 时,step+1,reach 更新为最大的 maxs
class Solution {
public:int jump(vector<int>& nums) {int steps = 0, i, reach = 0, maxs = 0;for(i = 0; i < nums.size()-1; ++i){maxs = max(maxs,nums[i]+i);if(i == reach){++steps;reach = maxs;}}return steps;}
};
2.2 BFS
class Solution {
public:int jump(vector<int>& nums) {queue<int> q;//idxint i, size, step = 0, tp, maxIdx = 0, nextIdx, n = nums.size();q.push(0);while(!q.empty()){size = q.size();while(size--){tp = q.front();if(tp >= n-1)return step;nextIdx = min(n-1,max(maxIdx, tp+nums[tp]));q.pop();for(i = maxIdx+1; i <= nextIdx; ++i)q.push(i);maxIdx = nextIdx;}step++;}return step;}
};
16 ms 8.4 MB