[LeetCode] 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 class Solution {
 2 private:
 3     int f[100000];
 4 public:
 5     int jump(int A[], int n) {
 6         // Start typing your C/C++ solution below
 7         // DO NOT write int main() function
 8         int maxPos = 0;
 9         f[0] = 0;
10         
11         for(int i = 0; i <= maxPos; i++)
12         {
13             int pos = i + A[i];
14             if (pos >= n)
15                 pos = n - 1;
16                 
17             if (pos > maxPos)
18             {
19                 for(int j = maxPos + 1; j <= pos; j++)
20                     f[j] = f[i] + 1;
21                 maxPos = pos; 
22             }
23             
24             if (maxPos == n - 1)
25                 return f[n-1];
26         }
27     }
28 };
posted @ 2012-11-25 20:53  chkkch  阅读(1671)  评论(0编辑  收藏  举报