55. Jump Game

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.
Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
給定一個數組,每個元素代表當前索引位置,你能跳躍的距離,問從0索引位置開始,你是否能跳到最后一個元素。

一、暴力解法,深度優先搜索的思路,即嘗試從位置0開始的所有跳法,但是這種方法有很多的重復計算,比如有n種方法都能跳到第i個位置,這個方法的時間復雜度是指數級別。

public boolean canJump1(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return true;
    }

    return helper(nums, 0);
}

public boolean helper(int[] nums, int index) {
    if (index == nums.length - 1) {
        return true;
    }

    int maxJump = nums[index];
    for (int i = index + 1; i <= index + maxJump; i++) {
        if (helper(nums, i)) {
            return true;
        }
    }

    return false;
}

二、動態規劃,對于每個位置i來說,如果它前面某個位置j可以被跳達并且這個位置的value大于等于i-j,那么i也是可以被跳達的。所以對于位置i來說,可以遍歷i前面的所有位置,只要有一個位置滿足上面的條件,位置i就是可以跳到的。下面是代碼,時間復雜度是n方,很可惜,leetcode居然提示超時。

public boolean canJump(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return true;
    }
    
    int n = nums.length;
    boolean[] dp = new boolean[n];
    dp[0] = true;
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (dp[j] && nums[j] >= i - j) {
                dp[i] = true;
                break;
            }
        }
    }
    
    return dp[n - 1];
}

三、貪心算法,貪心我覺得挺難想的,因為每道題貪心的思路都不一樣,下面就僅展示一下代碼吧。思路就是維持一個lastPos,如果前面某個點能跳到lastPos,就把lastPos更新為這個點,最后看lastPos是否是0,時間復雜度是n。

public boolean canJump(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return true;
    }
    
    int lastPos = nums.length - 1;
    for (int i = nums.length - 2; i >= 0; i--) {
        if (nums[i] + i >= lastPos) {
            lastPos = i;
        }
    }
    
    return lastPos == 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容