leetcode 之 Jump Game
来源:互联网 发布:telnet 80端口不通 编辑:程序博客网 时间:2024/06/17 12:58
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.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
class Solution {public: bool canJump(int A[], int n) { if(A == NULL || n <= 0)return false; int currentLeftStep = A[0],i; for(i = 1;i < n;++i) { if(--currentLeftStep < 0)return false; currentLeftStep = max(currentLeftStep,A[i]); } return true; }};
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.
For example:
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.)
class Solution {public: int jump(int A[], int n) { if(A == NULL || n <= 0)return 0; int i,j; vector<int> dp(n); for(i=n-1;i >= 0;--i)dp[i] = n-i-1;//初始化 for(i = n-2;i >= 0;--i) { for(j=i+1;j<=i+A[i] && j <= n;++j)dp[i] = min(dp[i],dp[j]+1); } return dp[0]; }};改进:思路仍然是动态规划,只是这次加上的贪心的味道。设dp[i]表示跳跃到节点i需要的次数,则我们从前往后遍历来计算dp[i],比如有j < k < i三个节点,则根据前面的定义,dp[j] < dp[k],则如果j可以跳到i,那么他的次数肯定小于k跳到i的次数,从而减少了计算的次数。
class Solution {public: int jump(int A[], int n) { if(n <= 0)return INT_MAX; vector<int> dp(n,INT_MAX);//dp[i]表示到节点i至少需要几次跳跃 dp[0] = 0; int i,j; for (i = 1;i < n;i++) { for (j = 0;j < i;j++) { if(A[j] + j >= i)//从节点j可以跳跃的最远距离 { if(dp[j] + 1 < dp[i]) { dp[i] = dp[j]+1;//找到的第一个一定是最小的 break; } } } } return dp[n-1]; }};
- LeetCode 之 Jump Game
- leetcode之Jump Game
- leetcode 之 Jump Game
- LeetCode之Jump Game
- Leetcode 之 Jump Game
- leetcode之jump game
- leetcode之Jump Game
- 【Leetcode】之 Jump Game
- leetcode之Jump Game && Jump Game II
- Leetcode之Jump Game & Jump Game II
- LeetCode之Jump Game II
- 【Leetcode】之Jump Game II
- leetcode之jump game II
- Leetcode之Jump Game问题
- LeetCode 之 Jump Game(贪心算法)
- LeetCode第45之 Jump Game II
- LeetCode进阶之路( Jump Game)
- Leetcode之Jump Game II 问题
- kmp算法的实现
- hdu2023求品均成绩
- CodeBlock 快捷键大全
- strcpy和memcpy的区别
- linux中pid gid tgid tid的区别和联系
- leetcode 之 Jump Game
- 常见编程题
- Linux下使用socket传输文件的C语言简单实现
- Eclipse+Spark 开发
- leetcode AC rates over 40%按从高到低
- 静态编译FFMPEG的指令并在工程引用.a文件
- 设置View渐变颜色
- Android WebView 因重定向无法正常goBack()解决方案
- jpa双向多对多关系