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. http://blog.csdn.net/linhuanmars/article/details/21356187
2. 很生动的解释: http://www.cnblogs.com/lichen782/p/leetcode_Jump_Game_II.html
public class Solution { // Method 2: O(n) // http://blog.csdn.net/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; } }