1. 程式人生 > >leetCode 45.Jump Game II (跳躍遊戲) 解題思路和方法

leetCode 45.Jump Game II (跳躍遊戲) 解題思路和方法

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 is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

思路:本題是典型的貪心演算法,題目難度上也不算難,貪心策略是每步前進的地方是下一步能達到的地方最遠。

詳細程式碼如下:

public class Solution {
    public int jump(int[] nums) {
    	/**
    	 * 本題用貪心法求解,
    	 * 貪心策略是在每一步可走步長內,走最大前進的步數
    	 */
        if(nums.length <= 1){
            return 0;
        }
        int index,max = 0;
        int step = 0,i= 0;
        while(i < nums.length){
        	//如果能直接一步走到最後,直接步數+1結束
            if(i + nums[i] >= nums.length - 1){
            	step++;
            	break;
            }
            max = 0;//每次都要初始化
            index = i+1;//記錄索引,最少前進1步
            for(int j = i+1; j-i <= nums[i];j++){//搜尋最大步長內行走最遠的那步
                if(max < nums[j] + j-i){
                    max = nums[j] + j-i;//記錄最大值
                    index = j;//記錄最大值索引
                }
            }
            i = index;//直接走到能走最遠的那步
            step++;//步長+1
        }
        return step;
    }
}