LeetCode OJ - Jump Game
来源:互联网 发布:哪个电视直播软件清晰 编辑:程序博客网 时间:2024/05/16 11:38
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
.
分析:采用DP思路,i 能否到n-1,通过 i 到 j 和 j 到n-1来判断,设dp[i]表示i能否到达n,则dp[i] = (i + a[i] > j) && dp[j] == true,边界为dp[n - 1] = true。时间复杂度与具体输入有关,不过应该是二阶时间复杂度。
class Solution {public: bool *dp; bool canJump(int A[], int n) { dp = new bool[n]; memset(dp, false, sizeof(A)); dp[n - 1] = true; for(int i = n - 2; i >= 0; i--) { for(int j = i + 1; j < n; j++) { if(i + A[i] < j) { break; } else if( (i + A[i] >= j) && (dp[j] == true) ) { dp[i] = true; break; } } } return dp[0]; }};
分析二:最简单的想法是DFS,时间复杂度太高,跳过
bool ret = false;DFS(A[], start) { if(start + A[start] >= n - 1) { ret = true; return ; } for(j = start; j < start + A[start]; j++) { if(A[j] > 0) DFS(A[], start + A[j]); } }
分析三:贪心算法,从0开始跳一直跳到 n - 1,若知道在 i 位置能跳X个单位,那么就可以知道i + 1位置能跳max(X - 1, A[i])个单位。max为贪心选择,而整个问题随着i增大而规模变小。每一次贪心选择,规模都变小,故可以用贪心选择。
class Solution {public: bool canJump(int A[], int n) { if(n == 0) return false; int step = A[0]; for(int i = 1; i < n; i++) { if(step == 0) return false; step = max(step - 1, A[i]); } return true; }};
0 0
- LeetCode OJ:Jump Game
- LeetCode OJ - Jump Game
- LeetCode OJ:Jump Game II
- LeetCode OJ - Jump Game II
- LeetCode OJ Jump Game II
- <LeetCode OJ> 55. Jump Game
- LeetCode OJ-55.Jump Game
- Leecode OJ Jump Game
- LeetCode OJ算法题(四十四):Jump Game II
- LeetCode OJ算法题(五十四):Jump Game
- LeetCode OJ 之 Jump Game (“跳跃”游戏 - 一)
- LeetCode OJ 之 Jump Game II(“跳跃”游戏 - 二)
- 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
- C语言 问号表达式记忆 表达式1?表达式2:表达式3
- 解决warning 1 line adds whitespace errors.
- jQuery Mobile的按钮
- 2014年临床助理医师考试如何缓解压力
- TLB与cache的深入分析
- LeetCode OJ - Jump Game
- Android项目用到的一些开源项目
- Linux x86_64 的TLB管理
- 去除文本框中 html元素
- top命令详解
- OCP 1Z0 052 104
- 17 oj 对象转换
- leetcode - Generate Parentheses
- 找出出现次数最多的几个数值