Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
Note:
You can assume that you can always reach the last index.
解题要点:
DP解法(超时):
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [len(nums)] * len(nums)
dp[0] = 0
for i in range(len(nums)):
for j in range(i):
if i <= j + nums[j]:
dp[i] = min(dp[i], dp[j] + 1)
return dp[-1]
BFS解:
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2: return 0
level = curmax = nextmax = i = 0
while curmax - i + 1 > 0:
level += 1
for j in range(i, curmax+1):
nextmax = max(nextmax, nums[j]+j)
if nextmax >= len(nums)-1: return level
i = j
curmax = nextmax
return 0
大神解(最优解):
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
jumps = curEnd = maxReach = 0
for i in range(len(nums)-1):
maxReach = max(maxReach, nums[i] + i)
if i == curEnd:
jumps += 1
curEnd = maxReach
return jumps