45. Jump Game II

Posted 小河沟大河沟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了45. Jump Game II相关的知识,希望对你有一定的参考价值。

45. Jump Game II

题目

 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.

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

Note:
You can assume that you can always reach the last index.

解析

  • 运用bfs的思想,更新每一层的start,end,判断是否到达数组结尾,返回bfs的层数
// 45. Jump Game II
class Solution_45 {
public:
    int jump(vector<int>& nums) {
        int n = nums.size(), step = 0;
        int start = 0, end = 0; //bfs每一层的开始结束位置 //每层结束更新
        while (end<n-1) //end<n时,end=n-1就可以结束了
        {
            step++;
            int maxend = end + 1;
            for (int i = start; i <= end;i++)
            {
                if (i+nums[i]>n)
                {
                    return step;
                }
                maxend = max(i+nums[i],maxend);
            }
            start = end + 1;
            end = maxend;
        }
        return step;
    }

    int jump(int A[], int n) {

        vector<int> vec(A,A+n);
        return jump(vec);
    }
};

题目来源

以上是关于45. Jump Game II的主要内容,如果未能解决你的问题,请参考以下文章

45. Jump Game II

55. 45. Jump Game II *HARD*

45. Jump Game II

45. Jump Game II

45. Jump Game II

45. Jump Game II