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

 

Example 1:

Input: nums = [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: nums = [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.

1. 贪心算法

  • 维护一个变量 reach,表示最远能到达的位置,初始化为0。遍历数组中每一个数字,如果当前坐标大于 reach 或者 reach 已经抵达最后一个位置则跳出循环,否则就更新 reach 的值为其和 i + nums[i] 中的较大值,其中 i + nums[i] 表示当前位置能到达的最大位置,参见代码如下:
class Solution {
public:
    bool canJump(vector& nums) {
        int reach = 0; // 表示最远能到达的位置,初始化为0
        
        int n = nums.size();
        for(int i = 0; i < n; i++) {
            if(i > reach || reach >= n -1)
                break;
            reach = max(reach, i + nums[i]);
        }
        
        return reach >= n - 1;
    }
};

2. 动态规划

  • 这道题说的是有一个非负整数的数组,每个数字表示在当前位置的最大跳力(这里的跳力指的是在当前位置为基础上能到达的最远位置),求判断能不能到达最后一个位置,这里可以用动态规划 Dynamic Programming 来解,维护一个一维数组 dp,其中 dp[i] 表示达到i位置时剩余的跳力,若到达某个位置时跳力为负了,说明无法到达该位置。接下来难点就是推导状态转移方程啦,想想啊,到达当前位置的剩余跳力跟什么有关呢,其实是跟上一个位置的剩余跳力(dp 值)和上一个位置新的跳力(nums 数组中的值)有关,这里新的跳力就是原数组中每个位置的数字,因为其代表了以当前位置为起点能到达的最远位置。所以当前位置的剩余跳力(dp 值)和当前位置新的跳力中的较大那个数决定了当前能到的最远距离,而下一个位置的剩余跳力(dp 值)就等于当前的这个较大值减去1,因为需要花一个跳力到达下一个位置,所以就有状态转移方程了:dp[i] = max(dp[i - 1], nums[i - 1]) - 1,如果当某一个时刻 dp 数组的值为负了,说明无法抵达当前位置,则直接返回 false,最后循环结束后直接返回 true  即可,参见代码如下:
class Solution {
public:
    bool canJump(vector& nums) {
        int n = nums.size();
        vector dp(n, 0);
        for(int i = 1; i < n; i++) {
            dp[i] = max(dp[i - 1], nums[i - 1]) - 1;
            if(dp[i] < 0)
                return false;
        }
        
        return true;
    }
};

参考资料

https://www.cnblogs.com/grandyang/p/4371526.html

你可能感兴趣的:(数据结构与算法)