LeetCode 跳跃游戏 II 贪心算法

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

示例:

输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
     从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

说明:

假设你总是可以到达数组的最后一个位置。

class Solution {
    public int jump(int[] nums) {
        int len=nums.length;
        if(len<=1) return 0; 
//         记录每次次跳可能的位置的下标(子问题)j
        int indexNums[]=new int[len];
        indexNums[0]=0;
        for(int step=1;step<len;step++){
            int lastStepIndex=indexNums[step-1];
            int nextIndex=lastStepIndex+nums[lastStepIndex];
            if(nextIndex>=len-1) return step;
            int maxIndex=lastStepIndex+1;
            for(int j=2;j<=nums[lastStepIndex];j++){
//                 找最大能跳到的下标
                int temp=lastStepIndex+j;
                if(nums[temp]+temp>=nums[maxIndex]+maxIndex) maxIndex=temp;       
        }
            indexNums[step]=maxIndex;
    }
         return len-1;
    }
}

猜你喜欢

转载自blog.csdn.net/Z_Y_D_/article/details/83054074