leetcode -- Jump Game-- 重点--Greedy
来源:互联网 发布:ug轮廓3d倒角编程技巧 编辑:程序博客网 时间:2024/04/30 10:26
https://leetcode.com/problems/jump-game/
思路1
ref: http://blog.csdn.net/hyperbolechi/article/details/44033241
这是个典型的贪心问题,为了check是否可以走到最后一格,我们需要check第一格能否走到第二格,第二格能否走到第三格,。。。。, 直到check到倒数第一格能够走到最后一格,只要中途有unreachable的,那么就False,否则就True。
我们需要记录从第一个数组格子到当前数组格子,所能reach到的最大的index,记为max_reach_index 注意不仅仅只考虑当前数组格子 index + A[index]作为这个所能reach的最大的index,要考虑当前数组格子以前的所有格子中所能reach到的最大index。
例如: [2, 1000000, 5, 6], 当index到2时,max_reach_index = 1000001
class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) <=1: return True max_reach_index = nums[0] for index in xrange(1, len(nums)):#注意这里是从1开始 if max_reach_index >= index:# it can reach to the next position max_reach_index = max(max_reach_index, nums[index] + index) else: return False return True
思路2
ref2: https://www.zybuluo.com/chanvee/note/58731
给定一个数组,判断从首位置能否到达最后一个位置。这个问题我们可以反过来看,如果从第n-1个位置能够到达第n个位置,那么我们就可以判断前面n-2个位置能否到达第n-1个位置,以此类推,如果最后能反推到第一个位置则说明可以,否则不行
class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ index = len(nums) - 1 for i in reversed(range(len(nums)-1)): if i + nums[i] >= index: index = i #这里不能在 <index的时候,就break,因为即便第n-1个位置不能reach到第n个位置,那么第n-2, n-3...这之前的jump可能很大,可以直接跨到第n个位置,即index所在的位置。所以只要最后index能够到0,那么就是true,否则就是false return not index
0 0
- leetcode -- Jump Game-- 重点--Greedy
- LeetCode 55/45 Jump Game I/II-----Greedy**
- leetcode -- Gas Station -- 跟jump game像,重点--贪心
- greedy: 55. Jump Game \ 455. Assign Cookies
- LeetCode Jump Game && Jump GameII
- [LeetCode]Jump Game II、Jump Game
- 【LeetCode】Jump Game & Jump Game II
- leetcode Jump Game & Jump Game II
- leetcode之Jump Game && Jump Game II
- [leetcode]Jump Game &&Jump Game II
- 【LeetCode】Jump Game && Jump Game II
- [Leetcode]Jump Game && Jump Game II
- Leetcode之Jump Game & Jump Game II
- Jump Game 和Jump Game II---LeetCode
- LeetCode-Jump Game & Jump Game II
- 【Leetcode】【python】Jump Game/Jump Game II
- LeetCode: Jump Game
- LeetCode: Jump Game II
- 【Java.Apache.Camel】
- Drools 入门例子
- Java 对象在内存中的存储
- python交互模式下清屏
- [Vim]
- leetcode -- Jump Game-- 重点--Greedy
- Xcod 常见错误
- js----创建节点和插入节点
- Python——OOP(2)
- HDOJ--1006
- ContentProvider启动时机问题简记
- ZOJ 2358 2481
- HDU 1242 Rescue
- 【Android 进阶(一)】Android MVP框架实现过程