45. Jump Game II
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.
class Solution(object):
def jump(self, nums):
if len(nums) == 1:
return 0
ans = 0
start = 0
while start < len(nums) and start + nums[start] < len(nums) - 1:
tmp_list = nums[start + 1: start + nums[start] + 1]
i = 0
max_jump = 0
max = 0
while i < nums[start]:
if start + i + 1 + tmp_list[i] > max_jump and nums[start + i + 1 + tmp_list[i]]:
max = i + start + 1
max_jump = start + i + 1 + tmp_list[i]
i += 1
start = max
ans += 1
return ans + 1
"""
:type nums: List[int]
:rtype: int
题解:
题目是给定一个列表nums, 给定下标i, nums[i]表示能从这个地方前进的最大步数。
现在从下标0开始,求到最后一个下标的最小步数。
第一想法是用动态规划,即用一个所有值均为无限大的数组step,用于存到这个位置所用的最小步数。
那么对于每一个i, k <= nums[i], step[i+k] = min(step[i] + 1, step[i+k])
但是发现会超时,仔细一想最坏的情况是O(n平方)的。
因此,换一个想法,使用贪心算法。
即对于一个当前位置i, 只需要找到他的下2跳能到的最远的位置即可。
即下一个位置应该为j = max{i + k + nums[i + k], 1 <= k <= nums[i] }
当然,要证明这一点。倘若存在一个这样的m不满足这个等式,即m < j,但是通过这个m的到达终点的步数更少。
那么在对于取定这个j的k,在下一跳的位置i+k中,根据算法的定义是一定不会漏掉这个m的,因此矛盾。
所以这个算法是可行的。