leetcode: Jump Game II
http://oj.leetcode.com/problems/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.)
思路:
对这种题还有什么好说的呢?动态规划!以给定的数组为例(从0开始计数),第3格走1步可以到第4格,第2格最多走1步到不了第4格,第1格最多可以走3步也能到第4格,第0格最多走2步到不了第4格。那么我们只要比较一下到第1格和第3格哪个需要的步数较少,然后加1就可以了。
1 class Solution { 2 public: 3 int calcSteps(int A[], int position, vector<int> &steps) { 4 if (-1 != steps[position]) { 5 return steps[position]; 6 } 7 8 int min = INT_MAX; 9 10 for (int i = position - 1; i >= 0; --i) { 11 if ((i + A[i]) >= position) { 12 if ((calcSteps(A, i, steps) + 1) < min) { 13 min = steps[i] + 1; 14 } 15 } 16 } 17 18 steps[position] = min; 19 20 return min; 21 } 22 23 int jump(int A[], int n) { 24 vector<int> steps(n, -1); 25 26 steps[0] = 0; 27 for (int i = 1; i <= min(A[0], n - 1); ++i) { 28 steps[i] = 1; 29 } 30 31 calcSteps(A, n - 1, steps); 32 33 return steps[n - 1]; 34 } 35 };