LeetCode Online Judge 题目C# 练习 - 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.)

 1         public static int JumpGameII(int[] A)
 2         {
 3             if (A.Length <= 1)
 4                 return 0;
 5 
 6             int[] MinJumps = new int[A.Length];
 7             MinJumps[0] = 0;
 8             int Min = Int32.MaxValue;
 9             for (int i = 1; i < A.Length; i++)
10             {
11                 Min = Int32.MaxValue;
12                 for (int j = 0; j < i; j++)
13                 {
14                     if (MinJumps[j] >= Min) //加快了一点速度
15                         continue;
16                     if (A[j] >= i - j)
17                         Min = Math.Min(Min, MinJumps[j] + 1);
18                 }
19                 MinJumps[i] = Min;
20             }
21 
22             return MinJumps[MinJumps.Length - 1];
23         }

代码分析:

  DP,而且是用到了所有之前的最佳结果。

posted @ 2012-09-14 22:39  ETCOW  阅读(366)  评论(0编辑  收藏  举报