45. Jump Game II (Array, DP)
2015-10-14 21:25
323 查看
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 =
The minimum number of jumps to reach the last index is
思路:此处不能用贪心算法,因为局部的最少跳数(到i位置的最少跳数),并不适用于全局。
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
1step from index 0 to 1, then
3steps to the last index.)
思路:此处不能用贪心算法,因为局部的最少跳数(到i位置的最少跳数),并不适用于全局。
class Solution { public: int jump(int A[], int n) { int maxPos = 0; //已经处理过最少步数的最远位置 int f ; //表示到i所需的最少步数 f[0] = 0; for(int i = 0; i <= maxPos; i++) { int pos = i + A[i]; //i能够到达的最远位置 if (pos >= n) pos = n - 1; if (pos > maxPos) { for(int j = maxPos + 1; j <= pos; j++) f[j] = f[i] + 1; //状态转移方程:注意i之后即使有其他位置x能到达j位置,步数必定>=这个值,因为f[i]<=f[x] if i<=x maxPos = pos; } if (maxPos == n - 1) return f[n-1]; } } };
相关文章推荐
- 网络协议
- 判断1000年-2000年之间的闰年
- BroadcastReceiver总结
- [BZOJ 1053] [HAOI2007]反素数ant 数论+搜索
- <面试题>java基础知识易错点
- NSUserDefaults 存储可变数组问题
- UVALive 4260 Fortune Card Game (Regionals 2008 Asia Taipei +DP)
- PostgreSQL & Oracle - 2 OLTP "update/select based primary key" & insert
- vi/vim 常用命令
- iOS地图 MapKit框架
- html和xml解析
- BZOJ 1978: [BeiJing2010]取数游戏 game( dp )
- 网络原理,以及虚拟机相关配置
- PostgreSQL & Oracle -1 OLTP "update/select based primary key" & insert
- 影像去条带
- 面试小结一:关于操作系统的面试题整理
- Floyd传递闭包-POJ-3660-Cow Contest
- [Python]模拟键盘同时按下几个按键
- 最短路径练习-POJ 1860 Currency Exchange
- 【codevs3269】混合背包 背包DP裸题