您的位置:首页 > 其它

leetcode -- Jump Game-- 重点--Greedy

2015-12-15 00:10 274 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: