Leetcode 45: 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.)
Note:
You can assume that you can always reach the last index.
1. DP solution, it times out with large input set.
1 public class Solution { 2 public int Jump(int[] nums) { 3 var dp = new int[nums.Length]; 4 dp[0] = 0; 5 6 int j = 1; 7 while (j < nums.Length) 8 { 9 dp[j] = Int32.MaxValue; 10 for (int i = j - 1; i >= 0; i--) 11 { 12 if (nums[i] >= j - i) 13 { 14 dp[j] = Math.Min(dp[j], dp[i] + 1); 15 } 16 } 17 18 j++; 19 } 20 21 return dp[dp.Length - 1]; 22 } 23 }
Another dp solution that also times out
1 public int JumpDp2(int[] nums) { 2 var dp = new int[nums.Length]; 3 dp[0] = 0; 4 5 for (int j = 1; j < dp.Length; j++) 6 { 7 dp[j] = Int32.MaxValue; 8 } 9 10 for (int j = 0; j < nums.Length; j++) 11 { 12 for (int i = 1; i <= nums[j] && j + i < dp.Length; i++) 13 { 14 dp[j + i] = Math.Min(dp[j + i], dp[j] + 1); 15 } 16 } 17 18 return dp[dp.Length - 1]; 19 }
Finally a accepted solution
1 public int Jump(int[] nums) { 2 if (nums.Length < 2) return 0; 3 int curStep = 1, maxReach = nums[0]; 4 5 int j = 1; 6 while (j < nums.Length && maxReach < nums.Length - 1) 7 { 8 var next = maxReach; 9 for (int i = j; i <= next; i++) 10 { 11 maxReach = Math.Max(maxReach, i + nums[i]); 12 } 13 14 curStep++; 15 j = next; 16 } 17 18 return curStep; 19 }