1. 程式人生 > >【leetcode】55. Jump Game 動態規劃解法

【leetcode】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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.
題意:

給定一個非負整數陣列,你最初位於陣列的第一個位置。

陣列中的每個元素代表你在該位置可以跳躍的最大長度。

判斷你是否能夠到達最後一個位置。

分析:
題意轉化成程式就是給定輸入陣列nums,初始位置cur為陣列下標0,終點final 下標為nums.size()-1.
我的解法流程即為從下標cur出發,我們一共有0~nums[cur]種跳躍長度,那麼我們再以跳躍之後的位置為起點去搜索,判斷是否可以到達final。
我們用一個記憶化陣列dp來標記對於位置i是否已經到達,初始為-1,不能到達為0,已經到達為1,這樣可以避免不必要的搜尋,防止棧溢位。
注意跳躍之後的位置不能超過final。
class Solution {
public:
    int dp[100010];
    bool dfs(vector<int>& nums, int cur, int final){
        if(~dp[cur]) return dp[cur];
        if(cur == final) return true;
        dp[cur] = 0;
        for(int i = 1;i <= nums[cur]; ++i){
            if(dfs(nums, min(cur+i, final), final)) return dp[cur] = 1, true;
        }
        return false;
    }
    bool canJump(vector<int>& nums) {
        memset(dp, -1, sizeof(dp));
        return dfs(nums, 0, nums.size()-1);
    }
};