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.
For example:
Given array A = [2,3,1,1,4]
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.)
分析:可以用DFS,不过时间复杂度很高。其次考虑DP或者贪心
思路一:DFS(A, 0, 1); 超时
int ret = 0;
DFS(A[], start, level) {
if(A[start] == 0) return;
if(start + A[start] >= n - 2) {
ret = min(ret, level);
return ;
}
for(i = start + 1; i < start + A[start]; i++) {
DFS(A, i, level + 1);
}
}
思路二:动态规划,要求i的最短跳步数,知道i+1前面所有的跳步数即可,从n - 1处二位迭代求出所有结果即可。设dp[i] 为在i位置最小跳步数。
int jump(int A[], int n) {
if(n == 1) return 0;
dp = new int[n];
for(int m = 0; m < n; m++) dp[m] = INT_MAX;
dp[n - 1] = 0;
for(int i = n - 2; i >= 0; i--) {
for(int j = i + 1; j <= i + A[i] && j < n; j++) {
if(j == n - 1 || dp[j]) {
dp[i] = _MIN(dp[i], dp[j] + 1);
}
}
}
if(dp[0] == INT_MAX) return 0;
return dp[0];
}
思路三:动态规划,设dp[i]为0到i的最小跳步数,则有dp[5] < dp[7]。若到5位置需要调X步,那么跳到7一定>= X步。故当求dp[i]时,只需要知道从左边起第一个能到达i位置的j(此时dp[j]最小,且j能调到i),dp[i] = dp[j] + 1; (个人觉得这个动态规划,跟上一个时间复杂度相当,leetcode测试用例特殊才让这一个通过)
class Solution {
int *dp;
public:
int jump(int A[], int n) {
if(n == 1) return 0;
dp = new int[n];
dp[0] = 0;
for(int i = 1; i < n; i++) {
for(int j = 0; j < i; j++) {
if(j+A[j] >= i) {
dp[i] = dp[j] + 1;
break;
}
}
}
return dp[n-1];
}
};
思路四:贪心算法。在i位置跳跃的范围为[i+1, i+A[i]],在其中找出跳跃位置最远的一个j。由于 j 跳跃范围更大,所以更可能得到更远的下一跳。更新i = j, 从左往右迭代。
class Solution {
int *dp;
public:
int jump(int A[], int n) {
if(n == 1) return 0;
int ret = 0;
int i= 0, newstart = 0;
while(true) {
if(i+A[i] >= n - 1) return ++ret; //当前能达到最后
int reach = 0;
for(int j = i + 1; j <= i+A[i]; j++) { //当前能跳入的范围
if(reach < j + A[j]) {
reach = j + A[j];
newstart = j;
}
}
i = newstart;
ret++;
}
return ret;
}
};