您的位置:首页 > 其它

【LeetCode】55、jump game

2017-09-08 19:22 495 查看
题目: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 = 
[2,3,1,1,4]
, return 
true
.

A = 
[3,2,1,0,4]
, return 
false
.
解: 一、这道题是典型的贪心算法。所谓贪心算法是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,他所做出的仅是在某种意义上的局部最优解。贪心算法没有固定的算法框架,算法设计的关键是贪心策略的选择。必须注意的是,贪心算法不是对所有问题都能得到整体最优解,选择的贪心策略必须具备无后效性,即某个状态以后的过程不会影响以前的状态,只与当前状态有关。所以对所采用的贪心策略一定要仔细分析其是否满足无后效性。
二、贪心算法的基本思路:
    1.建立数学模型来描述问题。
    2.把求解的问题分成若干个子问题。
    3.对每一子问题求解,得到子问题的局部最优解。
    4.把子问题的解局部最优解合成原来解问题的一个解。
三、对于这个问题:贪心,只需要时刻计算前位置和当前位置所能跳的最远长度,并始终和n作比较就可以:
1,若在任意pos位置出现maxstep为0的情况,则说明无法继续向前移动,返回false
2,若在任意pos位置出现maxstep+pos>=n说明可以完成最后一跳,返回true
四:https://segmentfault.com/a/1190000009666420 http://blog.csdn.net/zl87758539/article/details/51694895  基本按照这个解题

class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
G = nums[0] #记录能到达的最远位置
n = len(nums)
if n==0:
return False
if n==1:
return True
for i in range(n-1):
if G<i:
return False #在过程中已经不能到达索引位置
G = max(G, i+nums[i])
if G>=n-1:
return True
if G<n-1:
return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: