LeetCode--45. Jump Game II

问题链接:https://leetcode.com/problems/jump-game-ii/

这个问题是在https://blog.csdn.net/To_be_to_thought/article/details/84426854的Jump Game基础上深化而来,基本思路还是动态规划的思想。

我的思路是:维护一个动态规划数组dp,dp[i]表示当前数组位置i经过至少dp[i]步才能到达终点,先贴上我的效率低下的解法,算法时间复杂度为O(n^2),空间复杂度为O(n),该算法与最大增长序列算法代码几乎一样的:

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

上述算法虽然效率低下,但是易于理解。在讨论区看到一种贪心法,不太容易理解:

class Solution {
    public int jump(int[] nums) {
        if(nums.length < 2){
            return 0;
        }
        int curMaxReach = nums[0];
        int nextMaxReach = nums[0];
        int step = 1;
        for(int i = 0; i < nums.length; i++){
            if(i > curMaxReach){
                step++;
                curMaxReach = nextMaxReach;
            }
            if(nums[i] + i > nextMaxReach){
                nextMaxReach = nums[i] + i;
            }
        }
        return step;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值