您的位置:首页 > 其它

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

2013-11-08 09:37 441 查看
第一次遇到用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: