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 =
A =
[2,3,1,1,4], return
true.
A =
[3,2,1,0,4], return
false.
[解题报告]
一维DP,定义 jump[i]为从index 0 走到第i步时,剩余的最大步数。
那么转移方程可定义为
jump[i] = max(jump[i-1], A[i-1]) -1, i!=0
= 0 , i==0
然后从左往右扫描,当jump[i]<0的时候,意味着不可能走到i步,所以return false; 如果走到最右端,那么return true.
[Code]
1: bool canJump(int A[], int n) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: int* jump = new int[n];
5: jump[0] = 0;
6: for(int i=1; i < n; i++)
7: {
8: jump[i] = max(jump[i-1], A[i-1]) -1;
9: if(jump[i] <0)
10: return false;;
11: }
12: return jump[n-1] >=0;
13: }
Update, 3/14/2013
Just one round DP. No need an array to track the status. Refactor the code.
1: bool canJump(int A[], int n) {
2: int maxCover = 0;
3: for(int start =0; start<= maxCover && start<n; start++)
4: {
5: if(A[start]+start > maxCover)
6: maxCover = A[start]+start;
7: if(maxCover >= n-1) return true;
8: }
9: return false;
10: }
本文介绍了一种使用一维动态规划方法解决跳跃游戏问题的算法,通过定义状态跳转方程并从左至右扫描数组,判断是否能够到达数组末尾。
3693

被折叠的 条评论
为什么被折叠?



