LeetCode Jump Game II 前跳游戏II
来源:互联网 发布:阿里云更改发票抬头 编辑:程序博客网 时间:2024/05/16 01:58
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 is 2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
这个类型的题目,先不要想去用什么动态规划法,二分法等等,而是先要搞清楚它的游戏规则。
感觉题意还是不是那么清楚,需要先回答三个问题:
1 是否可以从任意位置取数?
2 是否可以利用重复数?
3 每取一个数是否需要跳尽?
答:
1 不可以,只能取当前位置的数
2 不可以
3 不用,不超跳就行,比如当前数是10,那么可以跳0到10步,当然我们不会跳0步。
下面两个算法都很简洁的。
第一个程序:
这个程序好理解点。
int jump(int A[], int n) {if(n==1) return 0;//注意:别忘了特殊情况判断!int i = 0, last = 0, maxIndex = 0, step = 0;while (i+A[i] < n-1)//=n-1的时候就已经到达尾端了,所以不是n{for (maxIndex = i; last <= i+A[i]; last++)if (last+A[last] >= maxIndex+A[maxIndex]) maxIndex=last;step++;i = maxIndex;}return ++step;}
这个程序也很简洁,动动手就能理解了。
http://discuss.leetcode.com/questions/223/jump-game-ii
int jump2(int A[], int n) {int ret = 0;int last = 0;int curr = 0;for (int i = 0; i < n; ++i) {if (i > last) {last = curr;++ret;}curr = max(curr, i+A[i]);}return ret;}
和上面的下标处理有一点点不一样。
//2014-1-27int jump(int A[], int n) {int num = 0;int rec_pos = 0;int max_step = 0;for (int i = 0;rec_pos < n-1; i++){if (A[i]+i > max_step) max_step = A[i]+i;if (i >= rec_pos){rec_pos = max_step;num++;max_step = 0;}}return num;}
- LeetCode Jump Game II 前跳游戏II
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- leetcode Jump Game II
- leetcode Jump Game II
- [LeetCode]Jump Game II
- [leetcode]Jump Game II
- LeetCode-Jump Game II
- [leetcode] Jump Game II
- LeetCode - Jump Game II
- LeetCode:Jump Game II
- LeetCode | Jump Game II
- 【Leetcode】Jump Game II
- LeetCode Jump Game II
- 字符串反转输出
- 用js获取下拉列表的值还有数字的值
- POJ-3083 Children of the Candy Corn(深搜,广搜)
- JAVA日期处理类总结:Date/Calendar/GregorianCalendar/DateFormat/SimpleDateFormat类
- 高级查询
- LeetCode Jump Game II 前跳游戏II
- 最全的vim快捷键
- 虚拟机网络连接方式和网络设置
- ASP.NET && 实验八 && 开发会员管理系统
- PHP实现快速排序与冒泡排序
- 10^4号遇骗遭遇未果の陈述版
- PHP笔记(4)强制转换
- 人群与社会——第四周
- MongoDB安装 Win7