1. 程式人生 > >LeetCode 跳躍遊戲 II 貪心演算法

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