[LeetCode]045-Jump Game II
来源:互联网 发布:家长监控软件 编辑:程序博客网 时间:2024/05/21 10:30
题目:
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.)
Solution:
思路:用DFS或BFS都可以做,但肯定超时了。
贪心算法的思想可以用在这。这段代码也是参考了其他博客而来的,理解起来有不少困难,结合例子来看会稍微容易点。
int jump(vector<int>& nums) { int n = nums.size(); int i; int maxstep = 0; int waitstep = 0; int step = 0; for(i = 0;i<n;i++) { if(waitstep < i) //设置waitstep,是保证它所跳的步数在范围内。超过了就需要跳了 { step++; waitstep = maxstep; //更新最大范围步数 } maxstep = max(maxstep,nums[i] + i);//最大范围 } return step; }
0 0
- LeetCode 045 Jump Game II
- [LeetCode]045-Jump Game II
- LeetCode 045 Jump Game II
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- leetcode Jump Game II
- leetcode Jump Game II
- [LeetCode]Jump Game II
- [leetcode]Jump Game II
- LeetCode-Jump Game II
- [leetcode] Jump Game II
- LeetCode - Jump Game II
- LeetCode:Jump Game II
- LeetCode | Jump Game II
- 数据库之基础3
- 数据选择控件
- 关于分词的一些解惑
- [引言]学习编程技术需要的基本条件
- js关于省市的二级下拉菜单联动
- [LeetCode]045-Jump Game II
- Java多线程之ThreadPoolExecutor
- 综合案例建模--失物招领管理系统的模型
- Python学习实例:编写一个记事本GUI
- 工作总结2-代码规范问题
- Dagger 2 before
- 假如从来没有开始,你怎么知道自己会不会很爱很爱那个人呢
- js中 关于复选框的多选和反选
- jquery的height()和javascript的height总结,js获取屏幕高度