标签:
题目描述:
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.
这个题是贪心的思路,到达一个点后,先走最长距离就可以得到到达下一个点最小跳数。
一开始用了深度优先遍历,这样不出意外,肯定是超时的~
public int jump(int[] nums) {
if(nums.length==1)
return 0;
List<Integer> list=new ArrayList<Integer>();
findPath(0, nums, 0, list);
list.sort((o1,o2)->{
if(o1>o2)
return 1;
else if(o1<o2)
return -1;
else return 0;
});
return list.get(0);
}
public void findPath(int startIndex,int[] nums,int havaPassed,List<Integer> list){
int maxdistance=nums[startIndex];
for(int i=maxdistance;i>0;i--){
if((startIndex+i)>=(nums.length-1)){
list.add(havaPassed+1);
return;
}
findPath(startIndex+i, nums, havaPassed+1, list);
}
}
然后想到了动态规划,但是好久没用过动态规划,自己写的这种有点变形,还是会超时~~~
public int jump(int[] nums) {
if(nums.length==1)
return 0;
int[] jumps=new int[nums.length];
Arrays.fill(jumps, Integer.MAX_VALUE);
jumps[0]=0;
for(int i=0;i<nums.length-1;i++){
if(i+nums[i]>=nums.length-1)
return jumps[i];
for(int j=1;j<=nums[i];j++){
if(i+j<nums.length){
jumps[i+j]=Integer.min(jumps[i]+1, jumps[i+j]);
}
}
}
return jumps[nums.length-1];
}
最后参考了他人的做法,发现就其实就差一点点,从前往后遍历,可以减少遍历的次数。
public int jump(int[] nums) {
if(nums.length==1)
return 0;
int[] dp=new int[nums.length];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0]=0;
for(int i=1;i<nums.length;i++)
{
for(int j=0;j<i;j++)
{
if(j+nums[j]>=i)
{
int tmp = dp[j]+1;
if(tmp < dp[i])
{
dp[i] = tmp;
break;
}
}
}
}
return dp[nums.length-1];
}
还有时间复杂度更低的贪心算法:
int jump(int A[]) {
int n=A.length;
int ret = 0;//当前跳数
int last = 0;//上一跳可达最远距离
int curr = 0;//当前一跳可达最远距离
for (int i = 0; i < n; ++i) {
//无法向前继跳直接返回
if(i>curr){
System.out.println("aaa");
return -1;
}
if (i > last) {
last = curr;
++ret;
}
//记录当前可达的最远点
curr = Integer.max(curr, i+A[i]);
}
return ret;
}
标签:
原文地址:http://blog.csdn.net/yeshiwu/article/details/51352169