Leetcode 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.

題目分析

這道題類似於跳棋,結果是返回一個能否到底end。因爲該步與前一步緊密聯繫,因此採用DP思想。
用變量far記錄跳棋能跳到最遠的距離
1. 如果當前可跳最長等於0,且能跳到的最遠距離小於等於該位置,那麼認爲跳棋不能跨越該位置,如果該位置恰巧爲end,則返回true,否則就返回false
2. 動態記錄可以可以跳到的最遠距離

源代碼

class Solution {
public:
    bool canJump(vector<int>& nums) {
        // DP
        //vector<bool> dp(nums.size(), false);
        //dp[0] = true;
        int far = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == 0 && far <= i && i != nums.size() - 1) {
                return false;
            } else {
                far = max(far, nums[i] + i);
            }
        }
        return true;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章