Jump Game
Dynamic Programming
, Greedy
Medium
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.
Determine if you are able to reach the last index.
Example 1:
Example 2:
Analysis
转化为子问题:
设n = nums.length
。问题是否能到达n - 1
,可以转化为:
是否n - 2
能否到达,以及从 n - 2
是否能到达n - 1
或者n - 3
是否能到达,并且从n - 2
是否能到达n - 1
或者n - 4
是否能到达,并且从n - 4
是否能到达n - 1
....
或者0
是否能到达,并且从0
是否能到达n - 1
因此可以设定动态规划状态dp[i]
: 从开始出发能否到达index = i
初始值dp[0] = true
, 第一个初始位置一定可以到达
dp[i] = false
代表dp[i]
不确定能否到达,需要在后续bottom-up过程中得到答案
那么转移方程为:
最终结果则是:
参考:https://leetcode.com/articles/jump-game/
其中还有top-down的记忆化搜索,bottom-up的动态规划,贪心greedy等方法。
Solution
DP - Bottom Up
Time O(n^2), Space O(n)
Greedy
Complexity Analysis
Time complexity : O(n). We are doing a single pass through the
nums
array, hencennsteps, wherennis the length of arraynums
.Space complexity : O(1). We are not using any extra memory.
Reference
Last updated