您的位置:首页 > 其它

leetcode: Jump Game

2015-03-21 11:42 363 查看


Jump Game (


Again!


)

Question
Solution

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.
For example:

A =
[2,3,1,1,4]
, return
true
.
A =
[3,2,1,0,4]
, return
false
.

Hide Tags
Array Greedy

算法思路:

其实只是关心最远能跳到的距离,这道题是动态规划的题目,所用到的方法跟是在Maximum Subarray中介绍的套路,

用“局部最优和全局最优解法”。我们维护一个到目前为止能跳到的最远距离,以及从当前一步出发能跳到的最远距离。

局部最优local=A[i]+i,而全局最优则是global=Math.max(global, local)。

大家还有什么更好的解法么?欢迎交流哈

bool canJump(int A[], int n) {
/* 其实只是关心最远能跳到的距离,这道题是动态规划的题目,所用到的方法跟是在Maximum Subarray中介绍的套路,
* 用“局部最优和全局最优解法”。我们维护一个到目前为止能跳到的最远距离,以及从当前一步出发能跳到的最远距离。
* 局部最优local=A[i]+i,而全局最优则是global=Math.max(global, local)。
*/
if (A == NULL || n <= 0)
return false;
int max = 0;
int i = 0;
/* i<=max必不可少,不然若为不可达状态时,会是死循环,
meaning就是 i 必须是可达的,若 i>max,则 i 这个下标是不可能达到的,那继续执行循环体肯定就是错误的。*/
while (i < n && i <= max)
{
if (i + A[i] > max)
max = i + A[i];
i++;
}
if (max >= n - 1)
return true;
return false;
}


上面的方法不是很直观,参考了博文http://blog.csdn.net/xiaozhuaixifu/article/details/13628465,我现在再换另外一种方法:

用maxLen保存能走的最远距离,每到一个i,如果能走的最远距离变大,则更新maxLen,

bool canJump(int a[],int n)
{
if (n <= 1)
return true;
if (a[0] >= n - 1)//从a[0]处就可以走到最后一个位置
return true;
int maxLen = a[0];//初始化
for (int i = 1; i < n-1; ++i)
{
if (maxLen >= i)//如果能到达i位置
{
if (i + a[i] >= n - 1)//从i位置可以到达最后一个位置
return true;
if (i + a[i]>maxLen)//更新能到达的最远距离
maxLen = i + a[i];
}
}
return false;
}
Jump Game2

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.)

int  Jump2(int* a, int n)
{
int* dp = new int
;
memset(dp, 0, sizeof(int)*n);
dp[0] = 0;
int pos = 0, maxPos=0;
for (int i = 0; i <=maxPos; i++)
{
pos = i + a[i];
if (pos >= n)
pos = n - 1;
if (pos>maxPos)
{
for (int j = maxPos+1; j <= pos; j++)
dp[j] = dp[i] + 1;
maxPos = pos;
}
if (maxPos == n - 1)
{
print(dp, n);
return dp[n - 1];
}
}
}
方法二:

int Jump2(int* a, int n)
{
int ret = 0;
int last = 0;
int curr = 0;
if (1 == n && a[0] == 0)
return 0;
for (int i = 0; i < n; ++i)
{
if (i>last)
{
last = curr;
ret++;
}
if (i + a[i] > curr)
curr = i + a[i];
if (curr == n - 1)
return ret + 1;
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: