问题链接:https://leetcode.com/problems/jump-game-ii/
这个问题是在https://blog.csdn.net/To_be_to_thought/article/details/84426854的Jump Game基础上深化而来,基本思路还是动态规划的思想。
我的思路是:维护一个动态规划数组dp,dp[i]表示当前数组位置i经过至少dp[i]步才能到达终点,先贴上我的效率低下的解法,算法时间复杂度为O(n^2),空间复杂度为O(n),该算法与最大增长序列算法代码几乎一样的:
class Solution {
public int jump(int[] nums) {
int n=nums.length;
int[] dp=new int[n];
Arrays.fill(dp,Integer.MAX_VALUE);
dp[n-1]=0;
for(int i=n-1;i>=0;i--)
{
if(dp[i]==Integer.MAX_VALUE)
continue;
for(int j=0;j<i;j++)
{
if(j+nums[j]>=i)
{
dp[j]=Math.min(dp[j],dp[i]+1);
}
}
}
return dp[0];
}
}
上述算法虽然效率低下,但是易于理解。在讨论区看到一种贪心法,不太容易理解:
class Solution {
public int jump(int[] nums) {
if(nums.length < 2){
return 0;
}
int curMaxReach = nums[0];
int nextMaxReach = nums[0];
int step = 1;
for(int i = 0; i < nums.length; i++){
if(i > curMaxReach){
step++;
curMaxReach = nextMaxReach;
}
if(nums[i] + i > nextMaxReach){
nextMaxReach = nums[i] + i;
}
}
return step;
}
}