classSolution(object): defcanJump(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) if n == 1: returnTrue f = [Falsefor _ inrange(n)] f[n-1] = True for i inrange(n-2, -1, -1): for j inrange(1, nums[i]+1): if f[i+j] == True: f[i] = True break return f[0]
优化后的倒序遍历
使用需要的step代替存储的可达数组
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution(object): defcanJump(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) step = 1 for i inrange(n-2, -1, -1): if nums[i] >= step: step = 0 step += 1 return step == 1
正向贪心
正向遍历,记录最远可达距离right
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defcanJump(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) right = 0 for i inrange(n): if i <= right: right = max(right, i + nums[i]) # 更新可达的最远点 if right >= n-1: returnTrue else: break returnFalse