Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
class Solution:
def canJump(self, nums: List[int]) -> bool:
@cache
def dp(i):
if i >= len(nums)-1:
return True
for j in range(i+1, i+nums[i]+1):
if dp(j):
return True
return False
return dp(0)
class Solution:
def canJump(self, nums: List[int]) -> bool:
N = len(nums)
if N == 1:
return True
dp = [False] * N
# basecase
dp[-1] = True
for i in range(len(nums)-1,-1,-1):
for j in range(i+1, min(i+nums[i]+1, N)):
if dp[j]:
dp[i] = True
break
return dp[0]
class Solution:
def canJump(self, nums: List[int]) -> bool:
N, top = len(nums), len(nums)-1
for i in range(N-2,-1,-1):
if (i + nums[i] >= top):
top = i
return True if (top == 0) else False