【Leetcode】Jump Game II (DP)
2014-11-10 09:26
369 查看
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 =
The minimum number of jumps to reach the last index is
from index 0 to 1, then
这道题的思路和I差不多,只是需要维护一个step来记录长度,也就是说只有超过了上次跳跃的最大长度,step才会增加。
代码如下
public static int jump(int[] A) {
if (A == null || A.length == 0)
return 0;
int lastDestination = 0;
int destination = 0;
int step = 0;
for (int i = 0; i <= destination && i < A.length; i++) {
if (i > lastDestination) {
step++;
lastDestination = destination;
}
destination = Math.max(destination, A[i] + i);
}
if (destination < A.length - 1)
return 0;
return step;
}
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
1step
from index 0 to 1, then
3steps to the last index.)
这道题的思路和I差不多,只是需要维护一个step来记录长度,也就是说只有超过了上次跳跃的最大长度,step才会增加。
代码如下
public static int jump(int[] A) {
if (A == null || A.length == 0)
return 0;
int lastDestination = 0;
int destination = 0;
int step = 0;
for (int i = 0; i <= destination && i < A.length; i++) {
if (i > lastDestination) {
step++;
lastDestination = destination;
}
destination = Math.max(destination, A[i] + i);
}
if (destination < A.length - 1)
return 0;
return step;
}
相关文章推荐
- [LeetCode]Jump Game II(贪心&&DP!!!!!)
- Jump Game II [leetcode] DP的两种思路
- LeetCode-45-Jump Game II DP
- LeetCode Jump Game II
- LeetCode: Jump Game II
- Leetcode:Jump Game II
- LeetCode: Jump Game II
- LeetCode_Jump Game II
- [leetcode]Jump Game II
- [leetcode刷题系列]Jump Game II
- LeetCode Online Judge 题目C# 练习 - Jump Game II
- [leetcode]Jump Game II
- [Leetcode] Jump Game II
- leetcode 114: Jump Game II
- leetcode Jump Game II
- leetcode jump game I&&II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- [LeetCode]Jump Game II、Jump Game
- [LeetCode]Jump Game II