45. Jump Game II

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

Analysis:

第一种方法我首先想到了通过深度优先搜索,然后在进行剪枝优化,但是很遗憾超时了。

第二种方法是采用dp算法,新建立一个数组用来保存每一步的最小步数,根据题意数据保证始终是有解的,所以只需要返回数组最后一个值即可。

方法三是采用贪心算法,保证每一步都争取跨越度都最大,最终使得总步数最小。

Code:

方法一:(超时了)才用的是dfs,然后进行适当的剪枝,发现还是会超时

class Solution {
    private int min_jump = Integer.MAX_VALUE;
    public int jump(int[] nums) {
        dfs(nums, 0, 0);
        return min_jump;
    }
    private void dfs(int[] nums, int cur, int tmp) {
        if(cur >= nums.length -1) {
            min_jump = Math.min(min_jump, tmp);
            return;
        }
        for(int i = 0; i < nums[cur]; i++) {
            if(tmp + 1 < min_jump) {
                dfs(nums, cur + i + 1, tmp + 1);    
            }
        }
    }
}

方法二:

class Solution {
    public int jump(int[] nums) {
        int[] dp = new int[nums.length];
        Arrays.fill(dp, nums.length + 1);
        dp[0] = 0;
        for(int i = 0; i < nums.length; i++) {
            for(int j = i + 1; j <= i + nums[i] && j < nums.length; j++) {
                dp[j] = Math.min(dp[j], dp[i] + 1);
            }
        }
        return dp[nums.length - 1];
    }
}

 方法三:(最优解)

class Solution {
    public int jump(int[] nums) {
        if(nums.length < 2)
            return 0;
        int min_jump = 1;
        int cur = 0;
        int next = cur;
        while(true) {
            if(nums[cur] + cur < nums.length - 1) {
                int maxDis = 0;
                for(int j = 1; j <= nums[cur]; j++) {
                    if(nums[cur + j] + cur + j > maxDis) {
                        maxDis = nums[cur + j] + cur + j;
                        next = cur + j;
                    }
                }
                cur = next;
                min_jump++;
            } else {
                break;
            }
        }
        return min_jump;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值