leetcode 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.

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个位置。

示例 1:

输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。

示例 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

方法一:回溯法
因为会有多个递归函数,所以数组较长时,会出现栈溢出,不推荐此方法

方法二:动态规划
创建一个新数组status,记录原数组每个元素的状态,能到达的为1,不能到达的为0,或者true,false。

class Solution {
    public boolean canJump(int[] nums) {
        int [] status = new int[nums.length];
        status[0]=1;
        for(int i=0;i<nums.length;i++){
        	if(status[i]==1){
        		int step = nums[i];
        		if(i+step>=nums.length-1){
        			status[nums.length-1]=1;
        			break;
        		}
        		for( j=1;j<=step;j++){
        			status[i+j]=1;
        		}
        	}
        }
        return status[nums.length-1]==1?true:false;
    }
}

方法三:贪心算法
思路:尽可能到达最远位置(贪心)。如果能到达某个位置,那一定能到达它前面的所有位置
方法:初始化最远位置为arr[0],然后遍历数组,判断当前位置能否到达(即是否在最远位置的范围内),如果在,则比较当前位置+跳数>最远位置,是就更新最远位置。如果当前位置不能达到,则退出
具体措施:遍历数组,每次都求一次当前位置所能到达的最远位置,并更新所能达到的最远位置k。遍历数组的一个新元素,和上一次的最远位置k进行比较,查看是否超出所能到达的最远位置,若超出,则返回flase,未超出,则对最远进行更新

class Solution {
    public boolean canJump(int[] nums) {
    	int k = nums[0];
        for(int i=0;i<nums.length;i++){
        	if(i>k){
        		return false;
        	}
        	if(nums[i]+i>k){
        		k=Math.max(k, nums[i]+i);
        		if(k>=nums.length-1){
        			return true;
        		}
        	}
        }
        return true;
    }
}
原文地址:https://www.cnblogs.com/vitasoy/p/11920815.html