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.)
用一个数组保存到index的最小的步数。 如果新的走法可以使得到index的最小步数变小,就更新之。最后返回对last index的最小步数。同时可以设置变量记录到目前为止可以到达的最远的index,用于剪枝。具体请看代码:
int jump(int A[], int n) { //C++ if(n == 1) return 0; int head = 0; vector<int> record(n,n); record[0] = 0; for(int i = 0; i < n; i++) { if(A[i] + i > head) { head = A[i] +i; for(int j = 1; j < n-i&&j <= A[i]; j++) if(record[i+j] > record[i]+1 ) { record[i+j] = record[i]+1; if(i+j == n-1) return record[i]+1; } } } return record[n-1]; }
原文地址:http://blog.csdn.net/chenlei0630/article/details/41451271