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<len;i++){
        	steps[i]=Integer.MAX_VALUE-1;
        }
        steps[nums.length-1]=0;//终点站最小步数为0;
        for(int i=len-2;i>=0;i--){  	
        	for(int j=0;j<=nums[i]&&(i+j)<len;j++){	     			
        			steps[i]=steps[i]>(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){
        	temp=0;
        	next=0;
        	if(index+nums[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;
    }

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值