[leetcode][55] Jump Game
Posted ekoeko
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode][55] Jump Game相关的知识,希望对你有一定的参考价值。
55. Jump Game
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.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
解析
从下标(index)为0的位置开始跳,跳的范围在nums[index]之内,判断是否可以到达终点。
参考答案
自己写的(没通过最后一个用例):
class Solution {
public boolean canJump(int[] nums) {
return backtrack(0, nums);
}
public boolean backtrack(int start, int[] nums) {
if (start == nums.length - 1 || nums[start] + start >= nums.length - 1) {
return true;
}
for (int i = start + nums[start]; i > start; i-- ) {
if (backtrack(i, nums)) return true;
}
return false;
}
}
我第一时间想到用回朔,其实这里应该用贪心,不需要记录跳的过程。
别人写的(贪心法):
class Solution {
public boolean canJump(int[] nums) {
int reachable = 0;
for (int i=0; i<nums.length; ++i) {
if (i > reachable) return false;
reachable = Math.max(reachable, i + nums[i]);
}
return true;
}
}
遍历整个数组,找到每步的最优解,如果出现i > reachable
就代表不能到达终点。
以上是关于[leetcode][55] Jump Game的主要内容,如果未能解决你的问题,请参考以下文章