45-跳跃游戏II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LaputaFallen/article/details/79951629

Description:

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.


Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.


问题描述

给定一个正整数数组,你最初在数组起始下标。
数组中每个元素代表你在当前下标处的最大的跳跃距离。
返回到达数组最后的下标所需的最少的跳跃数。

注意,输入确保你总能到达最后的下标。


我的做法是通过动态规划

解法1(动态规划)

class Solution {
    public int jump(int[] nums) {
        int len = nums.length;
        int[] dp = new int[len];
        //对数组初始化为最大值
        for(int i = 0;i < len;i++)  dp[i] = len;
        dp[0] = 0;

        for(int i = 1;i < len;i++){
            for(int j = 0;j < i;j++){
                //条件判断代表j下标可以跳跃到i并且可以使到达i的步数变少
                if(j + nums[j] >= i && dp[j] < dp[i]){
                    dp[i] = Math.min(dp[i], dp[j] + 1);
                    break;
                }
            }
        }

        return dp[len - 1];
    }
}

更好的做法,贪心
解法2(贪心)

class Solution {
    public int jump(int[] A) {
        /*
        step_count代表总步数
        last_jump_max代表上一个最远界
        current_jump代表正在被更新,下次使用的最远界
        */
        int step_count = 0, last_jump_max = 0, current_jump_max = 0;

        //迭代,更新current_jump,若到达上次最远界,jump增1,将last_jump_max置为current_jump_max
        for(int i = 0; i < A.length - 1; i++) {
            current_jump_max = Math.max(current_jump_max, i + A[i]);
            if( i == last_jump_max ) {
                step_count++;
                last_jump_max = current_jump_max;
            } 
        }

        return step_count;
    }
}
阅读更多

没有更多推荐了,返回首页