Leetcode Jump game I, II

本文解析了JumpGame I 和 II两个问题的算法实现,分别使用动态规划和贪心算法来判断是否能够到达数组最后一个位置及如何用最少步数到达终点。提供了详细的代码示例。
Jump game I

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.

[code]

public class Solution {
    public boolean canJump(int[] A) {
        if(A==null || A.length<2)return true;
        boolean dp[]=new boolean [A.length];
        Arrays.fill(dp, false);
        dp[0]=true;
        for(int i=1;i<A.length;i++)
        {
            int j=i-1;
            while(j>=0)
            {
                if(dp[j]==true && A[j]>=i-j)
                {
                    dp[i]=true;break;
                }
                j--;
            }
            if(j<0)dp[i]=false;
        }
        return dp[dp.length-1];
    }

}

Jump game II

reach the last index in the minimum number of jumps.

[code]

public class Solution {
    public int jump(int[] A) {
        if(A==null || A.length<2)return 0;
        int start=0, end=0, jumps=0;
        while(start<=end && end<A.length-1)
        {
            int max=end;
            for(int i=start;i<=end;i++)
            {
                max=Math.max(max, i+A[i]);
            }
            start=end+1;
            end=max;
            jumps++;
        }
        return jumps;
    }

}

[Thoughts]
做 I 的时候没有想到用贪心, 就用dp做了。
贪心的思想是每次找到能reach的最远距离,code也简洁很多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值