LeetCode每日一题: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 is2. (Jump1step from index 0 to 1, then3steps to the last index.)

问题分析

和上一题相比,我们用dp[i]表示到达i位置的最少步数,那么dp[i+1]~dp[i+A[i]]的最少步数就是dp[i]+1 了。

代码实现

public int jump(int[] A) {
        int[] dp = new int[A.length];
        Arrays.fill(dp, 0);
        for (int i = 0; i < A.length; i++) {
            int maxStep = Math.min(i + A[i], A.length - 1);
            for (int j = i + 1; j <= maxStep; j++) {
                if (dp[j] == 0) dp[j] = dp[i] + 1;
            }
            if (dp[A.length - 1] != 0) break;
        }
        return dp[A.length - 1];
    }

你可能感兴趣的:(LeetCode每日一题:jump game ii)