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个位置所用的最小步数,
超时的输入大概是25000,24999,….1…这样的,很自然的问题是,对于当前节点,有必要扫描它所有的后继节点吗?
一个重要的事实是,
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]; }};
>.<
- LeetCode --- 45. Jump Game II
- LeetCode 45.Jump Game II
- [Leetcode] 45. Jump Game II
- [leetcode] 45.Jump Game II
- [leetcode] 45.Jump Game II
- leetcode 45. Jump Game II
- LeetCode 45. Jump Game II
- LeetCode 45. Jump Game II
- leetcode.45. Jump Game II
- leetcode 45. Jump Game II
- leetcode 45. Jump Game II
- [LeetCode] 45. Jump Game II
- LeetCode 45. Jump Game II
- leetcode 45.Jump Game II
- leetcode 45. Jump Game II
- 【leetcode】45. Jump Game II
- LeetCode 45. Jump Game II
- LeetCode 45. Jump Game II
- DevExpress(11.1.8) 报表(web):dev控件 WebChartControl 图表(柱状图、饼状图、折线图)
- Android6.0触摸事件分发机制解读
- 数据库--基本知识
- 今天用vs编译revolver-master,解决报错的问题。
- 单例设计
- LeetCode 45. Jump Game II
- 3 了解printk
- 递归菜单 加减号 展开 收回
- Mysql 实践(三) 远程登录被拒绝问题1130 解决
- jQuery 3.0最终版发布,十大新特性眼前一亮
- KMP复习 找字符串
- Spring EL表达式
- OSG学习笔记16 - 对点选物体平移(鼠标点选物体)(物体随鼠标移动)(屏幕坐标转世界坐标)
- VC++ 从源代码到可执行文件,一般经过了哪几步的处理?