Two ideas of Jump Game II (leetcode) DP: leetcodedp
The first approach is:
Dp (I): Minimum number of steps required to reach position I
Dp (I) must be incremental, so from j = A [I] (starting from the farthest position), update the array until dp (j + I) <= dp (I) + 1
If it is removed, it will
Int jump (int A [], int n) {int * dp = new int [n]; // the minimum number of steps required by dp [I] To I memset (dp, 0x3f, sizeof (int) * n); dp [0] = 0; for (int I = 0; I <n; I ++) {for (int j = A [I]; j> 0; j --) {if (j + I> = n-1) return min (dp [n-1], dp [I] + 1); if (dp [j + I] <= dp [I] + 1) break; dp [j + I] = dp [I] + 1 ;}} return dp [n-1];}
Another idea is:
MaxPos (I): The farthest position in step I
int jump(int A[], int n) {vector<int> maxPos;maxPos.push_back(0);maxPos.push_back(A[0]);if (n <= 1)return 0;if (A[0] >= n - 1)return 1;for(int index = 2; index < n; index++){int max = 0;for (int k = maxPos[index - 2] + 1; k <= maxPos[index - 1]; k++){if (max < A[k] + k){max = A[k] + k;if (max >= n - 1)return index;}}maxPos.push_back(max);}return n;}
Because we only use the index-1 and index-2 locations of maxPos, we can further optimize the space for O (1). We can use two variables to record the current maximum and the previous maximum positions.
The solution discussed in leetcode is as follows:
int jump(int A[], int n) { int ret = 0; int last = 0; int curr = 0; for (int i = 0; i < n; ++i) { if (i > last) { last = curr; ++ret; } curr = max(curr, i+A[i]); } return ret; }