45. Jump Game II

来源:互联网 发布:大数据金融论文 编辑:程序博客网 时间:2024/05/14 03:38


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.

For example:
Given array A = [2,3,1,1,4]

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.



-------------------------------------------------------------------------------------------------------------------------------------------------------


When iterate the array, I set an edge for the Search phase, which means that if I exceeds the edge, the minstep must add one and the maxReach will be update. And when the last index is within the range of the edge, output the minstep.

[2, 3, 1, 1, 4]

First, the edge is 0; Second, after start iterate the array, it exceeds the edge 0 when reaching the A[0] and update the edge to 2; Third, after it reach the A[2], it exceeds the edge 2 and update the new edge to the maxReach 4. Finally, end of the array is inside the edge, output the minstep.


贪心思想,每次尽可能地扩大可到达的范围,扩大到不能再扩大就需要增加步数。


public int jump(int[] A) {    int maxReach = A[0];    int edge = 0;    int minstep = 0;        for(int i = 1; i < A.length; i++) {        if (i > edge) {            minstep += 1;            edge = maxReach;            if(edge > A.length - 1)                return minstep;        }        maxReach = Math.max(maxReach, A[i] + i);        if (maxReach == i):            return -1;    }        return minstep;} 



------------------------------------------------------------------------------------------------------------------------------------------------------------------------


其他思路1:

DSF + 剪枝,搜索从每个点出发能够到达的下一个点,维护一个数组,用于记录到达index(i)时的最小步数,若到达index(i)时的步数已经比当前最小值大,剪枝。

复杂度高,超时。


int min=Integer.MAX_VALUE;int[] currentmin;public int jump(int[] nums){int len=nums.length;currentmin=new int[len];Arrays.fill(currentmin, Integer.MAX_VALUE);dfs(nums, 0, len-1, 0);return min;}public void dfs(int[] nums,int k,int n,int times){if(k>n||times>currentmin[k])return ;if(k==n){if(times<min)min=times;return ;}int jumprange=nums[k];for(int i=k+jumprange;i>=k+1;i--)dfs(nums, i, n, times+1);if(times<currentmin[k])currentmin[k]=times;}



其他思路2:


动态规划,扫描数组,对index(i)建立一个链表, for(int a : list[i] ) 表示index(i) 可以由index(a)到达,取 【来源表】中最小步数+1 。

时间复杂度主要来自建立【来源表】,最大测试数据组无法通过。


int[] dp;public int jump(int[] nums){int len=nums.length;ArrayList<Integer>[] fromlist=new ArrayList[len];dp=new int[len];for(int i=0;i<len;i++)fromlist[i]=new ArrayList<>(40);for(int i=0;i<len;i++)for(int j=Math.min(len-1, i+nums[i]);j>=i+1;j--)fromlist[j].add(i);dp[0]=0;for(int i=1;i<len;i++){int min=Integer.MAX_VALUE;for(int a:fromlist[i])if(dp[a]<min)min=dp[a];dp[i]=min+1;}return dp[len-1];}


0 0
原创粉丝点击