题目:给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
链接 https://leetcode.cn/problems/jump-game
class Solution:
def canJump(self, nums: List[int]) -> bool:
i = 0
if nums[i] == 0 and len(nums) == 1:
return True
while i < len(nums):
# 跳到了0的位置就没法跳
if nums[i] == 0:
return False
# 跳的位置加上其接下来能跳的步数不小于数组长度,则一定能到
if i + nums[i] >= len(nums)-1:
return True
# 找出该位置能跳最远的位置
cur = 0
jump = i+1 # 记录其能跳最大位置的下标
for j in range(i+1,i+nums[i]+1):
temp = j + nums[j]
if temp >= cur:
cur = temp
jump = j
i = jump
我这个是贪心还是动规?已经分不清了

class Solution:
def canJump(self, nums: List[int]) -> bool:
n, rightmost = len(nums), 0
for i in range(n):
if i <= rightmost:
rightmost = max(rightmost, i + nums[i])
if rightmost >= n - 1:
return True
return False
复杂度分析
时间复杂度:O(n),其中 n 为数组的大小。只需要访问 nums 数组一遍,共 n 个位置。
空间复杂度:O(1),不需要额外的空间开销。
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/jump-game/solution/tiao-yue-you-xi-by-leetcode-solution/
class Solution {
public boolean canJump(int[] nums) {
int n = nums.length;
if(n == 1)return true;
for(int i = n - 2; i >= 0; i--){
if(nums[i] == 0){
int j = i - 1;
for(; j >= 0; j--){
if(nums[j] > i - j)break;
}
if(j < 0)return false;
}
}
return true;
}
}

class Solution:
def canJump(self, nums: List[int]) -> bool:
length = len(nums)
if length == 1:
return True
dp = nums[0]
if dp == 0:
return False
for i in range(1,length -1):
a = max(dp,i+nums[i])
if i == a:
return False
dp = a
return True
参照https://leetcode.cn/problems/jump-game/solution/dong-tai-gui-hua-by-lingyingdong-gbe7/修改的python代码