【LeetCode】Jump Game (一维动态规划 + 线性扫描)
来源:互联网 发布:怎样安装网络摄像头 编辑:程序博客网 时间:2024/04/27 22:32
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 = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
java code : 这题初看用DP的思路很清晰: 设DP[i] := 从第 i 个位置开始能否到底最后一个位置,那么转移方程很好写
dp[A.length - 1] = true; 看代码吧,不过会超时,因为复杂度是O(n^2)
public boolean canJump(int[] A){if(A.length <= 1)return true;if(A[0] >= (A.length - 1))return true;boolean[] dp = new boolean[A.length];dp[A.length - 1] = true;for(int i = A.length - 2; i >= 0; i--){if(i + A[i] >= A.length - 1){dp[i] = true;continue;}for(int j = i + 1; j < A.length - 1; j++){if(i + A[i] >= j){dp[i] |= dp[j];if(dp[i] == true)break;}}}boolean res = false;if(dp[0] == true)res = true;dp = null;return res;}
下面给出一种O(n)的算法:
我们用maxlength 维护一个从开始位置能到达的最远距离,然后判断在当前位置是否能够到底最后一个位置和当前位置是否可达,如果两个条件都满足,那么返回true,如果当前位置是0,并且最远距离不能超过当前位置,那么只能返回false 了,更新最远距离
java code : 416ms
public class Solution { public boolean canJump(int[] A) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(A.length <= 1)return true;if(A[0] >= (A.length - 1))return true;int maxlength = A[0];if(maxlength == 0) return false;for(int i = 1; i < A.length - 1; i++){if(maxlength >= i && (i + A[i]) >= A.length - 1)return true;if(maxlength <= i && A[i] == 0)return false;if((i + A[i]) > maxlength)maxlength = i + A[i];}return false; }}
顺便说一下我看讨论区有人贴出如此算法并且还过了:
class Solution {public: bool canJump(int A[], int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int i = 0; while( i < n-1) { if( A[i] == 0) return false; i += A[i]; } return i >= n-1; } };这个算法是错误的,因为有一组反列: A = {5,4,0,0,0,0,0}, 显然应该返回 false.
leetcode 的数据还是有点弱。
- 【LeetCode】Jump Game (一维动态规划 + 线性扫描)
- LeetCode (23) Jump Game (动态规划)
- Jump Game 动态规划
- jump-game(动态规划)
- 【一维dp_线性扫描】Word Break 、Best time to Buy and Sell Stocks |||、max subarray、jump game |||
- 【贪婪算法、动态规划】Jump Game II
- Jump Game 搜索 动态规划 贪心
- 03动态规划-01jump-game
- 贪心法、动态规划——jump-game,jump-gameII
- LeetCode 403. Frog Jump|动态规划
- 动态规划 hard LeetCode 403. Frog Jump
- Frog Jump--深度遍历,动态规划--leetcode
- 寻找最少次跳数 - 贪心VS动态规划 Jump Game 2
- leetcode做题总结,动态规划I(Triangle,Unique PathsI/II,Minimum Path Sum,Climbing Stairs,Jump Game,Word Break)
- LeetCode Jump Game && Jump GameII
- [LeetCode]Jump Game II、Jump Game
- 【LeetCode】Jump Game & Jump Game II
- leetcode Jump Game & Jump Game II
- dorado 7
- AIR的ane开发
- Linux Crontab 计划任务 命令详解
- 索引碎片和解决方法
- 收缩Oracle数据文件
- 【LeetCode】Jump Game (一维动态规划 + 线性扫描)
- 希尔排序【模板】
- ubuntu配置好FTP后总是上传失败
- hdu 1506 栈
- ThinkPHP模板替换与系统常量及应用
- 人事面试一百问
- 在迷惘中找到方向
- 十把快刀:高效免费的十大企业软件
- SQL Server 中的 CTE 递归查询