您的位置:首页 > 其它

45. Jump Game II (Array, DP)

2015-10-14 21:25 323 查看
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.)

思路:此处不能用贪心算法,因为局部的最少跳数(到i位置的最少跳数),并不适用于全局。

class Solution {
public:
int jump(int A[], int n) {
int maxPos = 0; //已经处理过最少步数的最远位置
int f
; //表示到i所需的最少步数
f[0] = 0;

for(int i = 0; i <= maxPos; i++)
{
int pos = i + A[i]; //i能够到达的最远位置
if (pos >= n)
pos = n - 1;

if (pos > maxPos)
{
for(int j = maxPos + 1; j <= pos; j++)
f[j] = f[i] + 1; //状态转移方程:注意i之后即使有其他位置x能到达j位置,步数必定>=这个值,因为f[i]<=f[x] if i<=x
maxPos = pos;
}

if (maxPos == n - 1)
return f[n-1];
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: