leetcode笔记:Jump Game II
2015-12-16 00:57
579 查看
一. 题目描述
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
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.)
二. 题目分析
该题的大意是,给定一个数组,每个元素代表从该位置可以往后跳的距离,问从第一个位置跳到最后一个位置至少需要跳多少次。
与 Jump Game 有所不同的是,Jump Game 询问该数组能否跳到最后一格,这道题要求算出跳的次数。解决的思路依旧是贪心,只需设置一个数组用来记录跳的路径即可。
三. 示例代码
四. 小结
类似的解题思路还有BFS,后期可以验证验证。
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.)
二. 题目分析
该题的大意是,给定一个数组,每个元素代表从该位置可以往后跳的距离,问从第一个位置跳到最后一个位置至少需要跳多少次。
与 Jump Game 有所不同的是,Jump Game 询问该数组能否跳到最后一格,这道题要求算出跳的次数。解决的思路依旧是贪心,只需设置一个数组用来记录跳的路径即可。
三. 示例代码
class Solution { public: int jump(int A[], int n) { int result = 0; // 当前已跳跃的次数 int last = 0; // 上一跳可达到的最远距离 int curr = 0; // 当前一跳可达到的最远距离 for (int i = 0; i < n; ++i) { // 无法向前继跳直接返回 if(i > curr) return -1; // 需要进行下次跳跃,则更新last和当前已执行的跳数result if (i > last) { last = curr; ++result; } // 更新当前可跳达的最远处 curr = max(curr, i+A[i]); } return result; } };
四. 小结
类似的解题思路还有BFS,后期可以验证验证。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性
- C++ Custom Control控件向父窗体发送对应的消息