leetCode练习(45)

题目:Jump Game II

难度:hard

问题描述:

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.

解题思路:

在没有最后一句note的时候,我想到的是使用动态规划算法,一步一步求出从n-1到n的最小步数min(n-1),n-2到n的最小步数min(n-2),0到n的最小步数为Min{1+min(1),2+min(2)`````1+min(nums[0])},思路很简单,具体代码如下:

public static int jump2(int[] nums) {	
        long[] steps=new long[nums.length];
        int len=nums.length;
        
        for(int i=0;i=0;i--){  	
        	for(int j=0;j<=nums[i]&&(i+j)(1+steps[i+j])?(1+steps[i+j]):steps[i];   
        	} 
        }
       System.out.println("最小"+steps[0]);
       return (int)steps[0]; 
    }

提交后显示超时,提示使用贪心算法,并且注意到了note,不管这么走都能到最后~,于是设计新的策略为,当前位置index+跳的步数I+下一位置可跳距离nums[index+i]最大。具体代码如下:

public static int jump(int[] nums) {
        int len=nums.length;
        int index=0;
        int steps=0;
        int temp=0;
        int next;
        int i;
        while(index=len-1){
        		System.out.println("最小"+(steps+1));
    			return steps+1;
    		}
        	for(i=1;i<=nums[index];i++){
        		if(i+nums[index+i]>temp){
        			next=i;
        			temp=i+nums[index+i];
        		}
        	}
        	steps++;
        	index=index+next;
        }
        System.out.println("最小"+steps);
        return steps;
    }

提交通过。不过这一办法不能保证是最优解,是为不足。




你可能感兴趣的:(leetCode)