[leetcode] 55. Jump Game
阿新 • • 發佈:2022-04-01
題目
You are given an integer array nums
. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, or false
otherwise.
Example 1:
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.
Example 2:
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.
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 105
思路
dfs遍歷所有情況,超時。
貪婪演算法,每個臺階的最大跳躍高度是i+nums[i],那麼維護當前跳躍的最大高度,如果這個最大高度跳不上當前的臺階,就是失敗。
程式碼
python版本:
# dfs,超時 class Solution: def canJump(self, nums: List[int]) -> bool: res = False def dfs(now): nonlocal res if res or now >= len(nums): return if now == len(nums)-1: res = True return [dfs(now+i) for i in range(nums[now], 0, -1)] dfs(0) return res # 貪婪 class Solution: def canJump(self, nums: List[int]) -> bool: maxn = 0 for i, num in enumerate(nums): if maxn < i: return False maxn = max(maxn, i+num) return True # 貪婪2,從後到前 class Solution: def canJump(self, nums: List[int]) -> bool: goal = nums[-1] for i in range(len(nums))[::-1]: if i+nums[i] >= goal: goal = i return goal == 0