LeetCode-JumpGameII

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

题目:

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.)

Subscribe to see which companies asked this question

思路:

1)用一个dp数组来记录到达当前位置的最小步数

packagedp;publicclassJumpGameII {publicintjump(int[] nums) {intlen =nums.length;int[] dp =newint[len];for(inti = 0; i < len; ++i)

dp[i]=Integer.MAX_VALUE;

dp[0] = 0;//In order to save time, we don't visit the elements which already been visited.intstart = 1;for(inti = 0; i < len - 1; ++i) {

start=go(i, nums[i], start, dp);

}returndp[len-1];

}//Get next start position.privateintgo(intcurrent,intstep,intstart,int[] dp) {inti =start;for(; i <= current + step && i < dp.length; ++i) {if(dp[i] > dp[current] + 1)

dp[i]= dp[current] + 1;

}returni;

}publicstaticvoidmain(String[] args) {//TODO Auto-generated method stubint[] nums = { 2,3,1,1,4};

JumpGameII j=newJumpGameII();

System.out.println(j.jump(nums));

}

}

2)不用数组,就直接往前移动,第一次扫走一步能到的地方,第二次扫走二步能到的地方,在这个过程中,只要碰到了最后一个位置,就终止,证明是最小步数。

packagedp;publicclassJumpGameII {publicintjump(int[] nums) {intlen;if((len = nums.length) == 1)return0;intcount = 0;intstart = 0;intend = 0;while(end <len) {intmostRight = 0;++count;for(intj = start; j <= end; ++j) {if(j + nums[j] >= len - 1)returncount;if(j + nums[j] >mostRight)

mostRight= j +nums[j];

}

start= end + 1;

end=mostRight;

}returncount;

}publicstaticvoidmain(String[] args) {//TODO Auto-generated method stubint[] nums = { 2,3,1,1,4};

JumpGameII j=newJumpGameII();

System.out.println(j.jump(nums));

}

}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航