问题:
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.)
参考问题:数组跳跃游戏 Jump Game
思路:
一、首先想到动态规划。数组H[ ], H[i]表示index从0到i的最少跳数。若H[i] = m,那么试图去更新i之后的m个位置的最少跳数。
可是,需要空间复杂度O(N)。
二、贪心算法。贪心就要每次都试图走的更远,意思并不是走到这一次所能走范围的最远,而是在这一次所能走范围里寻找下一次能走最远的位置。
这样的策略就是竭力要走的更远。
动态规划法:
int jump(int A[], int n) {
if(n < 2)
return 0;
int H[n];
memset(H, 0, sizeof(H));
H[0] = 0;
for(int i=0;i<n-1;i++)
{
int m = A[i];
if(i + m >= n-1)
return H[i] + 1;
for(int j=1;j<=m;j++)
{
if(H[i+j] == 0 || H[i+j] > H[i] + 1)
H[i+j] = H[i] + 1;
}
}
return H[n-1];
}
贪心算法:
// 贪心算法
int jump(int A[], int n) {
if(n < 2)
return 0;
int cur = 0;
int count = 1;
while(true)
{
if(cur + A[cur] >= n-1)
return count;
//在cur所能到达的范围里找一个能跳最远的
int max = cur + 1;
for(int i=cur+2;i<=cur+A[cur]; i++)
if(i + A[i] > max + A[max])
max = i;
cur = max;
count++;
}
}