LeetCode.55(45) Jump Game && II (经典的动态规划问题)

题目:

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.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

分析(原创):

class Solution {
    public boolean canJump(int[] nums) {
        //给定非负数的数组,每个元素表示你可以走的最大步数(意味着你可以选择更小的或者),判断是否可以走到最末尾
        //思路:先求出当前节点之前能到的最大值,与当前节点下标比较,若小于,说明根本无法到达该节点
        //直接返回false。若到达该节点,且该节点能到达的最大范围超过或者等于num的长度,则直接返回true。
        
        if(nums.length==0||nums==null) return true;
        
        //创建preSum数组表示当前节点能到达的最大范围
        int [] preSum=new int[nums.length];
        int max=0;
        for(int i=0;i=nums.length){
                //可以直接到达最后
                return true;
            }
            max=Math.max(max,preSum[i]);
        }
        
        return true;
    }
}

分析(参考答案):

class Solution {
    public boolean canJump(int[] nums) {
        int index = nums.length - 1;
        for (int i = nums.length - 2; i >= 0; i--) {
            if (nums[i] + i >= index) index = i;
        }
        return index == 0;
    }
}

题目45:

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Note:
You can assume that you can always reach the last index.

分析(原创):

class Solution {
    public int jump(int[] nums) {
        //动态规划问题,dp[i]记录到达i的最小步数
        //思路:使用一个变量记录每次范围内的边界值,同时更新可达最远
        
        int [] dp=new int[nums.length];
        dp[0]=0;
        int curIndex=0;
        int curMax=0;
        int max=nums[0];//当前可达最远范围

        for(int i=1;i



你可能感兴趣的:(LeetCode算法编程)