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即可。代码如下:

 class Solution {
public:
int jump(int A[], int n)
{
vector<int> dp(n,);
if(n==) return ; for(int i=;i<n;i++)
{
for(int j=;j<i;++j)
{
if(A[j]+j>=i)
{
dp[i]=dp[j]+;
break;
}
}
}
return dp[n-];
}
};

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

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

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

 class Solution {
public:
int jump(int A[], int n)
{
int curr=,maxLen=,count=;
for(int i=;i<n;++i)
{
if(i>curr)
{
curr=maxLen;
count++;
}
maxLen=max(maxLen,i+A[i]);
}
return count;
}
};

最新文章

  1. Hello 2017!
  2. apache httpclient cache 实现可缓存的http客户端
  3. Angular 2 要来了,Wijmo 已准备好迎接
  4. DSP using MATLAB 示例 Example3.19
  5. Sublime Text 3安装插件指南
  6. Swift3.0基础语法学习&lt;四&gt;
  7. windows 说“我爱你”
  8. netty启动过程
  9. String类与Date类的转换
  10. puppet aix之自动化用户管理
  11. 文件转换dll mingw
  12. JQuery - 判断radio是否选中,获取选中值
  13. js调取本地可执行文件exe
  14. 自动化测试基础篇--Selenium select下拉框
  15. java.lang.ClassCastException: java.lang.Short cannot be cast to java.lang.String(Short类型无法强转成String类型)
  16. python执行selenium报错
  17. linux文件系统比较
  18. P2322 [HNOI2006]最短母串问题
  19. STM32的操作过程,寄存器配置与调试过程(转载)
  20. PHP环境搭建-记录

热门文章

  1. Richardson成熟度模型
  2. 一种精准monkey测试的方法
  3. 关于Python的多重排序
  4. Xpath语法&amp;示例
  5. 《Effective C++》读书笔记 条款02 尽量以const,enum,inline替换#define
  6. cronolog:日志分割工具
  7. 关于excle导数据的一些代码笔记
  8. 【转载】图解Java常用数据结构(一)
  9. 各类4G手机进入工参模式查看手机信息
  10. 使用DataTables导出html表格