Leetcode
45. Jump Game II
Leeter
2021. 10. 20. 18:34
Description:
Given an array of non-negative integers nums, 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.
You can assume that you can always reach the last index.
'''
[1] brute force)
idea::
consider all cases
return min steps
'''
'''
[2] Dynamic programming)
idea::
when denoting F(n), which is min step to reach n th index,
then, F(n) = min(F(i),F(j),F(k),..., F(reacable from i,j,k to n))+1
code::
import math
dp=[math.inf for _ in range(len(nums))]
dp[0]=0
for i in range(len(dp)-1):
for jump in range(1,nums[i]+1):
if i+jump>=len(dp)
break
dp[i+jump]=min(dp[i+jump],dp[i]+1)
return dp[-1]
-T/C: O(n^2)
-S/C: O(n)
'''
class Solution:
def jump(self, nums: List[int]) -> int:
dp=[math.inf for _ in range(len(nums))]
dp[0]=0
for i in range(len(dp)-1):
for jump in range(1,nums[i]+1):
if i+jump>=len(dp):
break
dp[i+jump]=min(dp[i+jump],dp[i]+1)
return dp[-1]