DP动态规划专题八 :LeetCode 55. Jump Game II

LeetCode 55. 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.

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.

版本一:通用版本:0~n-1求出n的情况

    public int jump(int[] nums) {
        int[] dp = new int[nums.length];
        for (int i = 1; i < nums.length; i++) {
            int min = Integer.MAX_VALUE;
            for (int p = i - 1; p >= 0; p--) {
                if (p == 0 || dp[p] > 0) {
                    if (p + nums[p] >= i) {
                        min = Math.min(min, dp[p] + 1);
                    }
                } 
            }
            dp[i] = min;
        }
        return dp[nums.length - 1];
    }

版本2:优化版:从0开始向后走,每次都先走最大的步数,如果走到一个未走到的地方,那么给这里的dp赋值,此时的步数一定是最小的,如果已经走到最后,那么直接返回此时的步数。

优化的关键点:不在乎具体的路径,只在乎每个位置的答案是否为最佳,这个位置的答案可以有多个路径,但是只要这个位置上的值是最佳值即可。

    public int jump(int[] nums) {
        if(nums == null || nums.length < 2)return 0;
        int[] dp  = new int[nums.length];
        dp[0] = 0;
        for(int i = 0; i < nums.length; i++){
            for(int j = nums[i]; j >= 1; j--){
                if(i+j >= nums.length-1){
                    return 1 + dp[i];
                }
                if(dp[i+j] == 0)dp[i+j] = 1 + dp[i];
                else break;
            }
        }
        return dp[nums.length - 1];
    }

猜你喜欢

转载自blog.csdn.net/katrina95/article/details/85443510