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

解法

把数组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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值