https://leetcode.com/problems/jump-game-ii/
dp 会TLE
思路1 会TLE, 思路2可以AC
参考http://chaoren.is-programmer.com/posts/42912.html
要用贪心, 记录最远能到达的范围, 每次在这个范围内搜, 找出下一跳的最远范围, 更新最远范围和跳数。例如,[2,3,1,1,4], 这里首先maxreach = 2,那么第一步的时候,可以达到3,和1,最大的是3,所以这里选择贪心的思路,走到3.然后在3的范围内找maxreach,然后继续贪心走到目标。。。。
code 如下,但是结果却是TLE, 过不了最大的case, 因为这里求maxreach每次都是从0开始求,其实没必要,见思路1
class Solution:
# @param A, a list of integers
# @return an integer
def jump(self, A):
lenA = len(A); maxCanReach = 0; jumpNum = 0
if lenA == 1: return 0
while True:
jumpNum += 1
for i in xrange(maxCanReach + 1):
maxCanReach = max(maxCanReach, i + A[i])
if maxCanReach >= lenA - 1: return jumpNum
思路2 可以AC
参考http://yucoding.blogspot.hk/2013/01/leetcode-question-29-jump-game-ii.html, code也用的这个
http://www.cnblogs.com/zuoyuan/p/3781953.html
基本思路与思路1一样,用m记录当前点能够达到的最远的index,只是optimize了code,对当前点i,在其后面找一个j + A[j]最大的地方作为下一步要走到的地方。这里j理解为index,A[j]理解为j index可以向前走A[j] steps.
class Solution:
# @param A, a list of integers
# @return an integer
def jump(self, A):
m = 0
i = 0
res = 0
if (len(A)<=1):
return 0
while i<len(A):
m = max(m,A[i]+i)
if m>0:#这里就是说m == 0的时候,最远能达到的地方是index 0, 这样的话,就一直停在了index 0 这个地方,不能向前走一步。而实际上如果这里写成m >=0, 也是可以AC的。
res=res+1
if m>=len(A)-1:
return res
tmp=0
for j in xrange(i+1,m+1):
if (j+A[j]>tmp):
tmp = j+A[j]
i = j
return res
自己重写
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1: return 0#这句话容易掉
count = 0
m = 0
i = 0
while i < len(nums):
m = max(m, i + nums[i])
#print m
if m >= len(nums) - 1:
return count + 1
else:
tmp = i+1 + nums[i+1]#这里要以i+1为初值或者以0
tmp_idx = i+1#这里要以i+1为初值或者以0
for j in xrange(i + 1, m + 1):
if j + nums[j] > tmp:
tmp = j + nums[j]#这句话容易掉
tmp_idx = j
i = tmp_idx
count += 1