LeetCode 45. Jump Game II

来源:互联网 发布:库里篮下命中率数据 编辑:程序博客网 时间:2024/04/29 17:50

题目

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

解法

把数组A抽象为一个有向图,如下图。

这里写图片描述

接下来很自然的想法是DP,dp[i]表示从起点到第i个位置所用的最小步数,dp[i]=min(dp[i],dp[j]+1),EjiG。从前往后扫描一遍数组,更新当前节点后继节点的最小步数,返回最后一个节点的最小步数。然后,超时了!

超时的输入大概是25000,24999,….1…这样的,很自然的问题是,对于当前节点,有必要扫描它所有的后继节点吗?

一个重要的事实是,i,jdp,i<=jdp[i]<=dp[j],因为在每一个位置向前走的步数是连续的1,2,3…,而不是2,6,3,9…,能到达j的节点一定能到达i。如果i<=j,i,j有共同后继节点,i扫描过的节点,j不需要进行扫描,因为一定不会找到更小的步数。所以想法变为对于当前节点,从它的后继节点中第一个没有走过的节点开始扫描,更新最小步数,如果最后一个节点的dp值已得到更新,则直接返回。算法在最坏情况下的复杂度变为O(n)

class Solution {public:    int jump(vector<int>& nums) {        vector<int> d;        int bound = 0;       // 已经走到的最远的位置        for (int i = 0; i < nums.size(); i++) {            d.push_back(0);        }        for (int i = 0; i < nums.size(); i++) {            for (int j = bound - i + 1; j <= nums[i]; j++){//从后继节点中第一个没走到的节点开始扫描                if (i + j < nums.size()) {                    d[i + j] = d[i] + 1;                    if (i + j == d.size() - 1) {                        return d[i + j];                    }                }            }            bound = max(bound, i + nums[i]); // 更新走过的最远位置        }        return d[d.size() - 1];    }};

>.<

0 0
原创粉丝点击