每个位置i有一个最大跳跃距离,求最小步数从0跳到n-1。

  • dp[i]表示从0跳到i的最少步数,显然可以转移的状态就是从i-a[i]到i-1。
  • 因为是最小步数,考虑用优先队列优化,再考虑到状态有范围的,所以用单调队列,及时将失效的dp状态移除。

code

class Solution {
public:
int jump(vector<int>& nums) {
int n=nums.size();
vector<int> q(n,0);
vector<int> dp(n,0);
int l=0,r=-1;
dp[0]=0;
q[++r]=0;
for(int i=1;i<n;i++){
while(l<=r && q[l]+nums[q[l]]<i){
l++;
}
dp[i]=dp[q[l]]+1;
while(l<=r && dp[q[l]]>dp[i]){
r--;
}
q[++r]=i;
}
return dp[n-1];
}
};

Leetcode_45. 跳跃游戏 II的更多相关文章

  1. lintcode: 跳跃游戏 II

    跳跃游戏 II 给出一个非负整数数组,你最初定位在数组的第一个位置. 数组中的每个元素代表你在那个位置可以跳跃的最大长度. 你的目标是使用最少的跳跃次数到达数组的最后一个位置. 样例 给出数组A =  ...

  2. Leetcode力扣45题 跳跃游戏 II

    原题目: 跳跃游戏 II 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 你的目标是使用最少的跳跃次数到达数组的最后一个位置. 示例: 输入: ...

  3. LeetCode 45. 跳跃游戏 II | Python

    45. 跳跃游戏 II 题目来源:https://leetcode-cn.com/problems/jump-game-ii 题目 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素 ...

  4. Java实现 LeetCode 45 跳跃游戏 II(二)

    45. 跳跃游戏 II 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 你的目标是使用最少的跳跃次数到达数组的最后一个位置. 示例: 输入: [ ...

  5. [leetcode] 45. 跳跃游戏 II(Java)(动态规划)

    45. 跳跃游戏 II 动态规划 此题可以倒着想. 看示例: [2,3,1,1,4] 我们从后往前推,对于第4个数1,跳一次 对于第3个数1,显然只能跳到第4个数上,那么从第3个数开始跳到最后需要两次 ...

  6. leetcode 55. 跳跃游戏 及 45. 跳跃游戏 II

    55. 跳跃游戏 问题描述 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 判断你是否能够到达最后一个位置. 示例 1: 输入: [2,3,1, ...

  7. 【LeetCode每天一题】Jump Game II(跳跃游戏II)

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  8. LeetCode(45): 跳跃游戏 II

    Hard! 题目描述: 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 你的目标是使用最少的跳跃次数到达数组的最后一个位置. 示例: 输入: [ ...

  9. [LeetCode] 45. Jump Game II 跳跃游戏 II

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

随机推荐

  1. Personal Photo Experience Proposal

      Background:             Our smart phones are the most widely-used cameras now, more and more photo ...

  2. Treasure Island DFS +存图

    All of us love treasures, right? That's why young Vasya is heading for a Treasure Island. Treasure I ...

  3. kioptrix靶机记录

    靶机地址:172.16.1.193 Kali地址:172.16.1.107 首页为Apache测试页,没看到有价值信息 尝试目录扫描: 点击查看: http://172.16.1.193/index. ...

  4. SVM家族(一)

    SVM家族简史 故事要从20世纪50年代说起,1957年,一个叫做感知器的模型被提出, 1963年, Vapnikand Chervonenkis, 提出了最大间隔分类器,SVM诞生了. 1992年, ...

  5. 用SQL查询分析实现类似金蝶K3的收发存明细表

    使用SQL查询分析实现类收发存的报表,原始需求在 另外一篇文章 的第四部分.下图是实现需求. 一.准备 删除临时表 [buy]判断是否存在临时表,存在则删除[/buy] if OBJECT_ID('t ...

  6. tensorflow1.0 矩阵相乘

    import tensorflow as tf matrix1 = tf.constant([[3,3]]) matrix2 = tf.constant([[2],[2]]) product = tf ...

  7. qa问答机器人pysparnn问题的召回

    """ 构造召回的模型 """ from sklearn.feature_extraction.text import TfidfVecto ...

  8. pytorch 中的LSTM模块

  9. SourceTree for Windows跳过登录解决方法

    来源:https://blog.csdn.net/t_332741160/article/details/79611303 SourceTree 是一个强大的git管理客户端,但是在使用最新版需要登录 ...

  10. 解决Cannot use a scalar value as an array

    这是类型转换的问题,看看上方代码是不是先把布尔值或者0值赋给了一个变量,然后下面循环中又把这个变量当作数组用了