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.)
[分析] 自己的暴力方法仍然超时,搬大牛的解法,能理解正确性但目测现在还不能类似地举一反三,多练习几遍,我想慢慢会领悟其中的奥妙。
[ref]
1. [url]http://blog.youkuaiyun.com/linhuanmars/article/details/21356187[/url]
2. 很生动的解释:[url]http://www.cnblogs.com/lichen782/p/leetcode_Jump_Game_II.html[/url]
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.)
[分析] 自己的暴力方法仍然超时,搬大牛的解法,能理解正确性但目测现在还不能类似地举一反三,多练习几遍,我想慢慢会领悟其中的奥妙。
[ref]
1. [url]http://blog.youkuaiyun.com/linhuanmars/article/details/21356187[/url]
2. 很生动的解释:[url]http://www.cnblogs.com/lichen782/p/leetcode_Jump_Game_II.html[/url]
public class Solution {
// Method 2: O(n)
// http://blog.youkuaiyun.com/linhuanmars/article/details/21356187
public int jump(int[] nums) {
if (nums == null || nums.length <= 1)
return 0;
int N = nums.length;
int lastReach = 0, reach = 0;
int steps = 0;
for (int i = 0; i <= reach && i < N; i++) {
if (i > lastReach) {
steps++;
lastReach = reach;
}
reach = Math.max(reach, i + nums[i]);
}
return steps;
}
// Method 1: timeout
public int jump1(int[] nums) {
if (nums == null || nums.length <= 1)
return 0;
int N = nums.length;
int[] dp = new int[N];
dp[0] = 0;
for (int i = 1; i < N; i++) {
dp[i] = Integer.MAX_VALUE;
for (int j = 0; j < i; j++) {
if (j + nums[j] >= i)
dp[i] = Math.min(dp[i], dp[j] + 1);
}
}
if (dp[N - 1] < Integer.MAX_VALUE)
return dp[N - 1];
else
return -1;
}
}

本文探讨了如何使用贪心算法解决跳数游戏问题,通过分析实例和给出的代码实现,阐述了如何在有限步内达到游戏目标,提供了一种有效的方法论。
1203

被折叠的 条评论
为什么被折叠?



