
image.png
簡(jiǎn)潔標(biāo)準(zhǔn)解法:動(dòng)態(tài)規(guī)劃,dp[i]記錄nums[i]之前所能到達(dá)的最遠(yuǎn)距離,dp[i] = max(dp[i-1], i + nums[i]),空間優(yōu)化可以將dp[i]變?yōu)閐p (k)
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n=len(nums)
k=0
for i in range(n):
if i>k:
return False
k=max(k,i+nums[i])
return True
本人思路:下一步的位置由:能獲得(當(dāng)前已經(jīng)走的步數(shù)(cur_steps)+當(dāng)前能走的步數(shù)(j<=nums[i])+跳躍過去的那一步能走的步數(shù))的最大值確定,并且判斷如果上述的最大值已經(jīng)超過了跳到最后一步所需的步長(zhǎng),就返回True。
記得單獨(dú)判斷只有一步或者為空的情況。
犯錯(cuò)記錄:忘記在式子中寫入當(dāng)前實(shí)際走的步長(zhǎng)。
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n=len(nums)-1
max_steps=0
cur_steps=0
i = 0
if len(nums)<=1:
return True
while i<n:
nexti=i
for j in range(1,nums[i]+1):
if j+nums[i+j] > max_steps:
nexti=i+j
max_steps=j+nums[i+j]
if cur_steps+max_steps>=n:
return True
cur_steps+=nexti-i
max_steps=0
if i==nexti:
return False
i=nexti
return False