@(labuladong的算法小抄)[贪心]
leetcode 55. 跳跃游戏
题目描述
解题思路
每一步都计算一下从当前位置最远能够跳到哪里,然后和一个全局最优的最远位置 farthest 做对比,通过每一步的最优解,更新全局最优解
class Solution {
public boolean canJump(int[] nums) {
int n = nums.length;
int farest = 0;
for (int i = 0; i < n - 1; i++) {
/* 每一步都计算一下从当前位置最远能够跳到哪里 */
farest = Math.max(farest, i + nums[i]);
/* 可能碰到了 0,卡住跳不动了 */
if (farest <= i) return false;
}
return farest >= n - 1;
}
}
参考题解:pwrliang的回复
上面这种方法本质上是隐式(implict)BFS,我们维护一个最远能走到的距离farest,在维护该变量的过程中发现它的距离大于等于nums.length-1,那就能够到达末尾。如果看不太懂,放一个显式(explicit)BFS,能通过,只不过非常慢。
class Solution {
public boolean canJump(int[] nums) {
Queue<Integer> q = new LinkedList<>();
boolean[] visited = new boolean[nums.length];
q.offer(0);
while(!q.isEmpty()) {
for(int size=q.size(); size>0; size--) {
// idx is current position
int idx = q.remove();
// if this condition is true, we can find an answer
if(idx >= nums.length - 1) return true;
// i is the next rightmost position we can reach
for(int i=idx + 1; i < nums.length &&
i<=idx + nums[idx]; i++) {
if(visited[i]) continue;
visited[i] = true;
q.offer(i);
}
}
}
return false;
}
}