[leetcode] 45. Jump Game II 解题报告
2015-10-28 13:44
369 查看
题目链接:https://leetcode.com/problems/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 =
The minimum number of jumps to reach the last index is
from index 0 to 1, then
本题是一个动态规划题目,保存一个最大可到达的距离,并设置一个数组来保存到达每个位置最短的步数,最大可到达位置的状态转移方程为:
max(maxreach, A[i] + i);
即当前的位置加上当前最大可走的步数,如果本次更新了最大距离,则同样更新从上一个最大距离到这次最大距离之间位置的步数,要注意边界条件,就是最大到达距离超出了数组长度的时候要做一个判断。
代码如下:
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
1step
from index 0 to 1, then
3steps to the last index.)
本题是一个动态规划题目,保存一个最大可到达的距离,并设置一个数组来保存到达每个位置最短的步数,最大可到达位置的状态转移方程为:
max(maxreach, A[i] + i);
即当前的位置加上当前最大可走的步数,如果本次更新了最大距离,则同样更新从上一个最大距离到这次最大距离之间位置的步数,要注意边界条件,就是最大到达距离超出了数组长度的时候要做一个判断。
代码如下:
class Solution { public: int jump(vector<int>& nums) { vector<int> dp(nums.size(), INT_MAX); dp[0] = 0; int Max = 0, len = nums.size(); for(int i = 0; i < len; i++) { int tem = i+nums[i]; if(tem > Max) { for(int j = Max +1; j <= min(tem, len-1); j++) dp[j] = dp[i] + 1; Max = tem; if(Max >= nums.size()-1) return dp[nums.size()-1]; } } return 0; } };
相关文章推荐
- SCSS个人规范总结
- android 实现视频选取功能,包括视频录制和从图库选取
- SCSS个人规范总结
- PowerDesigner反向工程操作步骤 以PowerDesigner15为例
- Jstl标签<c:if>的用法
- Requests+Beautifulsou 自动登录v2ex并签到(python3.4逐行解释)
- struts2_11_实现自己的拦截器的定义
- 关于.net 2.0 remoting 中 TCP Channel 用户认证探讨(一)
- crm服务查询实体和实体的字段信息
- 软件设计模式
- hdu1244(dp)
- main函数可变参数问题代码
- Android开发之自动填写短信验证码
- Git fetch和git pull的区别
- Ajax融合struts2过程中,action类回传给客户端中文数据出现问号乱码的解决办法
- 学Android---CheckBox
- 拳头公司聊天服务架构:服务器篇
- Nginx 0.8.x + PHP 5.2.13(FastCGI)搭建胜过Apache十倍的Web服务器(第6版)[原创]
- JAVA 内存管理总结
- SQL Server 2008 压缩日志文件