[LeetCode] Jump Game 解题报告
来源:互联网 发布:ug10.0加工编程铣平面 编辑:程序博客网 时间:2024/05/15 23:50
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
.» Solve this problem
[解题报告]
一维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: }
0 0
- Leetcode Jump Game 解题报告
- 【LeetCode】Jump Game 解题报告
- [LeetCode] Jump Game 解题报告
- Leetcode Jump Game II 解题报告
- 【LeetCode】Jump Game II 解题报告
- [leetcode] 55. Jump Game 解题报告
- [leetcode] 45. Jump Game II 解题报告
- [LeetCode] Jump Game II 解题报告
- leetcode解题报告:45. Jump Game II
- LeetCode解题报告 55. Jump Game [medium]
- [Leetcode] 45. Jump Game II 解题报告
- [Leetcode] 55. Jump Game 解题报告
- LeetCode 55. Jump Game 解题报告
- Leetcode #45. Jump Game II 跳跃游戏2 解题报告
- Leetcode #55. Jump Game 跳跃游戏 解题报告
- 55. Jump Game解题报告
- leetcode解题方案--045-- Jump Game II
- [Leetcode] 403. Frog Jump 解题报告
- [LeetCode] Implement strStr() 解题报告
- [LeetCode] Insert Interval 解题报告
- [LeetCode] Integer to Roman 解题报告
- [LeetCode] Interleaving String 解题报告
- 采用dlopen、dlsym、dlclose加载动态链接库【总结】
- [LeetCode] Jump Game 解题报告
- [LeetCode] Jump Game II 解题报告
- [LeetCode] Largest Rectangle in Histogram 解题报告
- [Leetcode] Length of Last Word 解题报告
- [LeetCode] Letter Combinations of a Phone Number 解题报告
- [LeetCode] Longest Common Prefix 解题报告
- [LeetCode] Longest Palindromic Substring 解题报告
- Android网络缓存的实现思路
- [LeetCode] Longest Substring Without Repeating Characters 解题报告