题目:

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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

代码:

class Solution {
public:
bool canJump(vector<int>& nums)
{
return Solution::dfs(nums, );
}
static bool dfs(vector<int>& nums, int index)
{
if ( index>=nums.size()- ) return true;
if ( nums[index]== ) return false;
for ( int i = nums[index] ; i >= ; --i )
{
if ( Solution::dfs(nums, index+i) ) return true;
}
return false;
}
};

tips:

随手写了一个DFS Solution,结果是对的但是超时,shit...

====================================

由于不会Greedy的算法,一心想写一个dp solution,结果最后dp没写成,写成了个greedy;不过代码还是很简洁和高效的:

class Solution {
public:
bool canJump(vector<int>& nums)
{
int max_jump = ;
max_jump = std::max(max_jump, nums[]);
for ( int i = ; i<=max_jump; ++i )
{
if ( max_jump>=nums.size()- ) return true;
max_jump = std::max(max_jump, i+nums[i]);
}
return false;
}
};

tips:

算法的时间复杂度O(n),空间复杂度O(1)。

正常往后迭代变量,每次迭代变量后,维护一个max_jump(即走到元素i,已知可以走到最远的元素下标)。

如果下标大于等于nums.size()-1,则返回true;如果遍历到max_jump了,且没有到达nums.size()-1,则返回false。

后来想想能不能用dp或者dfs再解一次,但想来想去,dp或者dfs解法的核心无非还是变形的greedy,没有太大意思。完毕。

===============================================

第二次过这道题,直接写了greedy的AC了。

class Solution {
public:
bool canJump(vector<int>& nums) {
if ( nums.size()== ) return false;
int maxLength = ;
for ( int i=; i<=maxLength; ++i )
{
if ( i+nums[i]>maxLength )
{
maxLength = i+nums[i];
}
if ( maxLength>=nums.size()- ) return true;
}
return maxLength>=nums.size()-;
}
};

最新文章

  1. Win10 HOSTS锁定 无法提权 修改 解决办法 100%有效
  2. ArcGIS JS 学习笔记1 用ArcGIS JS 实现仿百度地图的距离量测和面积量测
  3. maven test 运行 指定类或方法 打包 mvn clean assembly:assembly
  4. Android ListView滑动过程中图片显示重复错乱闪烁问题解决
  5. vbox下android分辨率设置
  6. 怎么知道RTL Schematic中的instance与哪段代码对应呢
  7. swift入门-day01
  8. BZOJ 1025 [SCOI2009]游戏
  9. date tod = boost::gregorian::day_clock::local_day(); //当前日期
  10. MEF初体验之十二:Composition Batch
  11. Blend4开发:会飞的小鸟
  12. c# Winform Invoke 的用法
  13. js分析 猫_眼_电_影 字体文件 @font-face
  14. Rstudio+mysql写入中文表
  15. 第 2 章 容器架构 - 008 - Docker 组件如何协作?
  16. JQuery中2个等号与3个等号的区别
  17. Shell变量知识进阶
  18. Hive-表连接
  19. ubuntu 如何进行文件、夹删除等操作
  20. GNU 是什么?

热门文章

  1. Nagios-4.1.1 (OpenLogic CentOS 7.2)
  2. Hyper-V 2016 配置管理系列(应用篇)
  3. windows 7 X64 提示“com surrogate 已停止工作”的解决方案
  4. 新建snmp模型总结
  5. POJ-2135 Farm Tour---最小费用最大流模板题(构图)
  6. 2018.5.29 Oracle连接到空闲例程
  7. python_52_函数返回值2
  8. java 如何使的float保留2位或者多位小数
  9. AngularJS 历经实例
  10. POJ 2406 Power String