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= 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) {
                    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 maxreach) {
                maxreach = i+A[i];
                cnt++;
            }
            if(maxreach >= A.length-1)    return cnt;
        }
        
        return cnt;
    }




你可能感兴趣的:(Leetcode,LeetCode专栏)