您的位置:首页 > 其它

[LeetCode]45 Jump Game II

2015-01-03 09:16 323 查看
https://oj.leetcode.com/problems/jump-game-ii/
http://blog.csdn.net/linhuanmars/article/details/21356187
public class Solution {
public int jump(int[] A)
{
// Solution A:
// return jump_Gready(A);

// Solution B:
return jump_DP(A);
}

////////////////////////////
// Solution B: DP
//
private int jump_DP(int[] A)
{
if (A == null || A.length <= 1)
return 0;

int global = 0;
int local = 0;
int step = 0;
int lastreach = 0;

for(int i = 0 ; i < A.length ; i ++)
{
if(i > lastreach)
{
step++;
lastreach = global;
}

local = i + A[i];
global = Math.max(global, local);

// If cannot reach
if (global <= i && i != A.length - 1)
return -1;
}

return step;
}

////////////////////////////
// Solution A: Gready
//
private int jump_Gready(int[] A)
{
// [2, 3, 1, 1, 4]
// [2, 1, 2, 1, 0]

if (A == null || A.length <= 1)
return 0;

int len = A.length;
int start = 0;
int end = 0;
int jump = 0;
while (end < len)
{
int maxCanGo = 0;
jump ++;
for (int i = start ; i <= end ; i ++)
{
int curValue = A[i] + i;
if (curValue >= len - 1)
{
// Reached
return jump;
}

if (curValue > maxCanGo)
{
maxCanGo = curValue;
}
}

if (maxCanGo <= end)
{
// Can not go further
return -1;
}

start = end + 1;
end = maxCanGo;
}

return jump;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode