045 Jump Game II[H]

1 题目描述

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.

Your goal is to reach the last index in the minimum number of jumps.

难度:Hard

2 题目样例

For example:

Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2.

 (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

3 题意分析

这个题目的题设很有意思,大概和我们小时候玩的一种”跳房子”游戏类似:格子上的数字是多少,就意味着可以往前最多走多少步。

这个题目求的是走到最后一格所要经历的最少格子数。(也就是最少的jump的次数)

4 思路分析

说是用动态规划,实际上我觉得这么简单的动态规划很难算是真正的动态规划。= =(个人的偏见是无论如何也得有两层循环嵌套啊!这题目被标记为Hard有点高了。手动狗头.jpg)

用ans表示目前为止jump的次数,

mx表示从0~i这i+1个元素中能到达的最远的格子数,

reach表示从初始位置进行ans次jump能到达的最远的格子数。

当reach小于i时,说明ans次jump已经不足以到达当前第i个元素,所以要把ans+1,使之达到记录的mx。

代码实现如下:

class Solution

{
    
public:
    
    int jump(vector<int>& nums)
    
    {
        int n=nums.size();
        
        int ans=0;
        
        int mx=0;
        
        int reach=0;
        
        for(int i=0;i<n;i++)
            
        {
            if(reach<i)
                
            {
                ans++;
                
                reach=mx;
            }
            
            mx=max(mx,nums[i]+i);
        }
        
        return ans;
    }
    
};

5 后记

我很好奇这个题目为什么叫Jump Game II,按理来说有II应该先有I才对。

直到我在这道题的后边发现了Jump Game…

为什么会是这种先有鸡后有蛋的调调啊!(摔)

    原文作者:Lolita
    原文地址: https://zhuanlan.zhihu.com/p/34448960
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞