[Leetcode] 45. Jumping Game II (Java) (Dynamic planning)

Source: Internet
Author: User

45. Jumping Game II

Dynamic planning
This question can be poured out of consideration.
See Example:
[2,3,1,1,4]
We push forward from behind, for the 4th number 1, jump once
For the 3rd number 1, obviously can only jump to the 4th number, then jump from the 3rd number to the last need two times
For the 2nd number 3, apparently one step, jump once
For the first number 2, you can only choose to skip or jump two times, obviously choose to jump a more profitable, and eventually just jump two times

When backward pushing, it is found that satisfying ① optimal substructure and ② overlapping sub-problem. You can use dynamic planning.

Status Description: F[i] Indicates the minimum number of times I need to jump to the last position in the first position
State transition equation: f[i] = min (f[i+1]~f[nums[i]) +1
Initial conditions F[nums.length () -1]=0

class Solution {    public int jump(int[] nums) {        int f[] = new int[nums.length];        if (nums.length == 0) {            return 0;        }        if (nums.length == 1) {            return 0;        }        f[nums.length - 1] = 0;        for (int i = nums.length - 2; i >= 0; i--) {            f[i] = findMin(f, i, nums[i]) + 1;            if (f[i] < 0) f[i] = Integer.MAX_VALUE;        }        return f[0];    }    private int findMin(int[] f, int i, int num) {        int min = Integer.MAX_VALUE;        for (int j = 1; j <= num && i + j < f.length; j++) {            min = Math.min(min, f[i + j]);        }        return min;    }}

[Leetcode] 45. Jumping Game II (Java) (Dynamic planning)

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.