[Leetcode] 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 is2. (Jump1step from index 0 to 1, then3steps to the last index.)

题意:问最小的跳跃次数

思路:这题是jump game 的扩展。这题有两种解法:

第一种是动态规划,定义数组dp,dp[i]表示到达i处的最小跳跃次数。关键在确定dp[i]的值,我们可以遍历i之前的元素值,找到第一次能跳到或跳过i的下标,然后在其基础上加1即可。代码如下:

 1 class Solution {
 2 public:
 3     int jump(int A[], int n) 
 4     {
 5         vector<int> dp(n,0);
 6         if(n==0)    return 0;
 7 
 8         for(int i=0;i<n;i++)
 9         {
10             for(int j=0;j<i;++j)
11             {
12                 if(A[j]+j>=i)
13                 {
14                     dp[i]=dp[j]+1;
15                     break;
16                 }
17             }
18         }    
19         return dp[n-1];      
20     }
21 };

 这种解法大的集合过不了。

第二种是贪心算法。其实个人觉得两种思路差不多,只是这种方法去掉了一些不必要的计算。遍历数组,找到当前能到达的最远距离curr,则,在这个距离中,不断的更新能到达的最远距离maxlen,遍历数组,若出了curr的范围,则计数器加1,并重新更新cur,至于i是如何出cur的范围不考虑。如:{3,3,1,1,4},

第一个3能达到的最远距离是curr,遍历数组,记下3到curr之间最新的最大距离maxlen,当i大于curr时,我们可以一步到达maxlen所在的位置,也就是说,我们不关心,从3到curr是如何到达的。参考了实验室小纸贴校外版的博客。代码如下:

 1 class Solution {
 2 public:
 3     int jump(int A[], int n) 
 4     {
 5         int curr=0,maxLen=0,count=0;
 6         for(int i=0;i<n;++i)
 7         {
 8             if(i>curr)
 9             {
10                 curr=maxLen;
11                 count++;
12             }
13             maxLen=max(maxLen,i+A[i]);
14         } 
15         return count;
16     }
17 };

 

posted @ 2017-07-14 15:34  王大咩的图书馆  阅读(767)  评论(0编辑  收藏  举报