Jump Game II 跳跃游戏(求跳到最后一个的最小步数) @LeetCode

第一次遇到用DP还超时的问题!既然DP都超时,那么只能再一次用greedy了。不过好歹想出了DP的solution

贪心的思想是用尽可能少得步子走完,一个重要思想是不断更新target位置,使得target不断向前移动

package Level4;

import java.util.Arrays;

/**
 * Jump Game II 
 * 
 *  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.)
 *
 */
public class S45 {

	public static void main(String[] args) {
		int[] A = {2,3,1,1,4};
		System.out.println(jump(A));
	}
	
	// 经典DP,但是TLE
	public static int jump(int[] A) {
        int[] jmp = new int[A.length];
        jmp[0] = 0;
        for(int i=1; i<A.length; i++){
        	jmp[i] = Integer.MAX_VALUE;
        	for(int j=0; j<i; j++){
        		if(i-j <= A[j]){
        			jmp[i] = Math.min(jmp[i], jmp[j]+1);
        		}
        	}
        }
//        System.out.println(Arrays.toString(jmp));
        return jmp[A.length-1];
    }

	// Greedy 在DP超时情况下,只能试着用greedy了!AC
	public static int jump2(int[] A) {

		int jmp = 0;
		int dest = A.length-1;		// destination index
		
		while(dest != 0){		// 不断向前移动dest
			for(int i=0; i<dest; i++){
				if(i+A[i] >= dest){		// 说明从i位置能1步到达dest的位置
					dest = i;		// 更新dest位置,下一步就是计算要几步能调到当前i的位置
					jmp++;
					break;		// 没必要再继续找,因为越早找到的i肯定越靠前,说明这一跳的距离越远
				}
			}
		}
		return jmp;
	}

}



public class Solution {
    public int jump(int[] A) {
        int target = A.length-1;
        int cnt = 0;
        while(target > 0) {
            for(int i=0; i<target; i++) {
                if(i+A[i] >= target) {
                    target = i;
                    cnt++;
                }
            }
        }
        return cnt;
    }
}



    public int jump(int[] A) {
        // write your code here
        
        int maxreach = 0;
        int cnt = 0;
        for(int i=0; i<A.length; i++) {
            if(maxreach < i)   return -1;
            if(i+A[i] > maxreach) {
                maxreach = i+A[i];
                cnt++;
            }
            if(maxreach >= A.length-1)    return cnt;
        }
        
        return cnt;
    }




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值