[LeetCode] Jump Game
来源:互联网 发布:昆明网页美工培训 编辑:程序博客网 时间:2024/06/06 05:56
Jump Game
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.
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
解题思路:本题给的提示是Greedy,但是Greedy很明显存在重复计算的问题啊?看了网上的一些解法,很明显没有考虑到重复计算的去除问题。
重复计算的产生:如下图,在位置A,B,C中都会发现D是可以选择的节点,所以会在D位计算3次。
根据动态规划中的技巧,巧妙的用一个数据来存储计算中的中间值,程序算法复杂度O(n),个人感觉比贪心算法好多了。
public class Solution { /** * @param A: A list of integers * @return: The boolean answer */ public boolean canJump(int[] A) { if(A.length <= 1) return true; boolean[] step = new boolean[A.length]; step[0] = true; for(int i=0;i<A.length;i++){ if(step[i] == true && A[i]>0){ for(int j=i+1;j<=i+A[i] && j < A.length;j++) step[j] = true; } } return step[step.length-1]; }}
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.
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.)
public class Solution { /** * @param A: A list of lists of integers * @return: An integer */ public int jump(int[] A) { if(A.length==1) return 0; boolean[] step = new boolean[A.length]; step[0] = true; int n = 0; while(true){ n++; for(int i=A.length-1;i>=0;i--){ if(step[i]){ for(int j=i+A[i];j>i;j--){ if(j >= A.length-1) return n; step[j] = true; } } } } }}
- LeetCode Jump Game && Jump GameII
- [LeetCode]Jump Game II、Jump Game
- 【LeetCode】Jump Game & Jump Game II
- leetcode Jump Game & Jump Game II
- leetcode之Jump Game && Jump Game II
- [leetcode]Jump Game &&Jump Game II
- 【LeetCode】Jump Game && Jump Game II
- [Leetcode]Jump Game && Jump Game II
- Leetcode之Jump Game & Jump Game II
- Jump Game 和Jump Game II---LeetCode
- LeetCode-Jump Game & Jump Game II
- 【Leetcode】【python】Jump Game/Jump Game II
- LeetCode: Jump Game
- LeetCode: Jump Game II
- LeetCode Jump Game
- LeetCode Jump Game II
- LeetCode : Jump Game
- LeetCode: Jump Game II
- spring整合mybatis
- 面向对象第六课,static变量和方法,内存分析
- hdu 5171 GTY's birthday gift (矩阵快速幂求类斐波那契数列)
- 统计与概率基础
- ORA-10567: Redo is inconsistent with data block
- [LeetCode] Jump Game
- android开发之android应用程序的组成
- jmeter下载安装以及插件安装(一)
- 苹果 App Store 申请和管理相关知识
- Lua解析Html的正则表达式Demo
- securecrt使用教程、SecureCRT配置详细图文教程
- 做好同行评审的24个细节
- Django学习:一张图看懂Django中mvc框架
- HTML head 元素