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.

例子

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.

分析

首先考虑dp,空间复杂度为O(n),时间复杂度为O(n^2),超时;
再考虑bfs,先列出从起点出发能跳到的节点,再列出从这些节点出发能跳到的节点......直到跳到终点。记录bfs的层数。

要点

dp/dfs

时间复杂度

O(n)

空间复杂度

O(1)

代码

class Solution {
public:
    int jump(vector<int>& nums) {
        if (nums.size() < 2) return 0;
        // i:数组下标 level: bfs层数
        // curRange: 当前能跳到的最远范围
        // nextRange: 下一步能跳到的最远范围
        int i = 0, level = 0, curRange = 0, nextRange = 0;
        while (i <= curRange) {
            level++;
            for (; i <= curRange; i++) {
                nextRange = max(nextRange, i + nums[i]);
                if (nextRange >= nums.size() - 1) return level;
            }
            curRange = nextRange;
        }
        return 0;
    }
};

扩展

如果问题中数组的元素表示只能跳的步数(原题目为能跳的最大步数),那么可能会有一些节点会跳不到,但还可以用bfs在O(n)时间内解决。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容