【Leetcode】Jump Game #55
来源:互联网 发布:阿里云搭建ftp 编辑:程序博客网 时间:2024/05/16 03:12
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.
Determine if you are able to reach the last index.
For example:
A =
A =
[2,3,1,1,4]
, return true
.A =
url: https://leetcode.com/problems/jump-game/[3,2,1,0,4]
, return false
.基本思路:
采用动态规划,答案存储在vector ans中。
假定我们在判断第i元素是否可以到达last element,则
ans[i] = true, if
1.i element 可以直接到达最后, 或者
2. 有j在i+ nums[i]范围内可以到达最后
注意本题需要剪枝
<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">如果ans[j] == false,那我们可以直接从ans[k], k = j + nums[j] + 1 开始查起。从ans[j]到ans[k]之间的元素必为false</span>
<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">证明:</span>
如果ans[j] == false,且 j 至 j + nums[j] + 1元素间有一元素可以到达最后,
则ans[j]应该为true,与假设相反。
bool canJump(vector<int>& nums) { vector<bool> ans(nums.size(), false); for (int i = nums.size()-1; i >= 0; --i) { int maxStep = nums[i]; int remainingStep = nums.size() - i - 1; if (maxStep >= remainingStep) { ans[i] = true; } else { int j = i+1; while (j <= maxStep+i) { if (ans[j] == true) { ans[i] = true; break; } j = j + nums[j] + 1; } } } return ans[0]; }
另附leetcode上一个不错的答案:
bool canJump(int* nums, int n) { int goal=n-1, i; for (i=n; i--;) if (i+nums[i] >= goal) goal=i; return !goal;}
0 0
- LeetCode 55: Jump Game
- [leetcode 55] Jump Game
- LeetCode(55) Jump Game
- [LeetCode 55]Jump Game
- leetcode || 55、Jump Game
- LeetCode-55-Jump Game
- leetcode-55 Jump Game
- Jump Game - LeetCode 55
- 【Leetcode】Jump Game #55
- Leetcode #55 Jump Game
- 【LeetCode】55:Jump Game
- LeetCode(55) Jump Game
- Leetcode#55||Jump Game
- (leetcode #55)Jump Game
- Leetcode 55 - Jump Game
- 【leetcode】【55】Jump Game
- LeetCode 55 - Jump Game
- 【LeetCode-55】Jump Game
- 移植eclipse项目遇到的问题
- VS2013配置opencv
- linux 文件操作库函数
- iOS毛玻璃效果的实现
- gcc编译C语言
- 【Leetcode】Jump Game #55
- 放在这里,看看能不能养出儿子?
- LeetCode 题解(122): House Robber II
- 自己动手开发简易的Web服务器
- 蚂蚁爬杆之动态演示
- 2015062801 - 祈福八仙水上乐园
- Eight reasons I rejected your article
- 8 reasons I accepted your article
- Opencv调用摄像头