Two ideas of Jump Game II (leetcode) DP: leetcodedp

Source: Internet
Author: User

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;    }





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.