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.

看到這個題目的時候,我第一反應是和字符串拼接題很像,可以採用動態規劃,對F[i]等於 F[j] && nums[j] >= (i -j) 的並集(0 <= j < i),實現之後發現最大測試集過不了,後面仔細分析題目,其實不是對於每個元素都要這樣判斷,要進行這樣判斷的唯一條件是:F[i - 1] == false && nums[i - 1] == 0,除此之外,都直接可以到達,既F[i] = true,這樣修改下代碼就ok。從這個題目也可以看出,做題還是得認真分析,不能想當然的,不然可能答案就是錯的,或者不是最優的。

class Solution {
public:
    //動態規劃
    bool canJump(vector<int>& nums) {
        int len = nums.size();
        if(len  < 2)
        {
            return true;
        }
        
        bool *F = new bool[len];
        for(int i = 0; i < len; ++i)
        {
            F[i] = false;
        }
        
        if(nums[0] > 0)
        {
            F[0] = true;
        }
        
        for(int i = 1; i < len; ++i)
        {
            if(!F[i - 1] || nums[i - 1] == 0)
            {
                for(int j = 0; j < i - 1; ++j)
                {
                    if(F[j] && nums[j] >= (i - j))
                    {
                        F[i] = true;
                        break;
                    }
                }
            }
            else
            {
                F[i] = true;
            }
        }
        
        return F[len - 1];
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章