分析:只要元素的值为0的那一步才有可能无法到达顶端。但是,如果它前面的元素能够跳过这个0,则仍然可以到达顶端。
相关算法:贪心算法(作者也在学习中)
代码:
class Solution:
# @param {integer[]} nums
# @return {boolean}
def canJump(self, nums):
if 0 not in nums:
return True
self.num = copy.deepcopy(nums)
location_0 = []
for i in range(len(nums)-1):
if nums[i] == 0:
location_0.append(i)
self.locations = copy.deepcopy(location_0)
for location in location_0:
self.is_arrive(location)
if self.locations == []:
return True
else:
return False
def is_arrive(self, location):
i = location-1
while i>= 0:
if i + self.num[i] > location:
self.locations.remove(location)
return
i = i - 1