57. Jump Game && Jump Game II

Jump Game

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.

思路:若能走的最远距离小于当前距离,说明走不过来。否则,利用此位置情况更新最远距离。

class Solution {
public:
bool canJump(int A[], int n) {
int reached = 0;
for(int i = 0; i < n; ++i) {
if(reached < i) return false;
if(i+A[i] > reached) reached = i+A[i];
}
return true;
}
};

Jump Game II

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

思路:

方法1: 动态规划。(能走到下标为 n-1 位置时,就结束。)

class Solution {
public:
int jump(int A[], int n) {
if(n == 0) return 0;
vector<int> step(n, INT_MAX);
step[0] = 0;
int reached = 0;
for(int i = 0; i < n-1; ++i) {
if(reached < i || step[i] >= step[n-1]) break;
if(i + A[i] > reached) {
reached = i+A[i];
for(int j = i+1; j < n && j <= reached; ++j)
step[j] = min(step[j], step[i]+1);
}
}
return step[n-1];
}
};

方法二 : 从前往后跳,每一步长内选择选择能跳到下一步长最远的点。 第一个步长为 0 - A[0], 第二步长为 A[0] - max(0+A[0],..., A[0] + A[A[0]]),

从 0->A[0]->maxA[i](0+A[0],...,A[i] + A[A[i]], ... , A[0] + A[A[0]]);

class Solution {
public:
int jump(int A[], int n) {
int last = 0, step = 0, maxV = 0;
for(int i = 0; i < n; ++i) {
if(i > last) {
last = maxV;
++step;
}
maxV = max(maxV, i + A[i]);
}
return step;
}
};

方法三: 从后往前确定应该走的位置。(从前往后遍历,如果 i + A[i] >= last , 说明其第一个能走到最后, 更新 last = i).

class Solution {
public:
int jump(int A[], int n) {
int last = n-1, step = 0;
while(last > 0) {
for(int i = 0; i < last; ++i) {
if(i+A[i] >= last) {
last = i;
step++;
break;
}
else if(i == last) return INT_MAX;
}
}
return step;
}
};

附加:以下这个代码也可以 AC. (但是常识上不觉得是对的)

class Solution {
public:
int jump(int A[], int n) {
int last = n-1, step = 0;
while(last > 0) {
for(int i = 0; i < last; ++i) {
if(i+A[i] >= last) {
last = i;
step++;
}
}
}
return step;
}
};
上一篇:web项目长时间未操作,退出登录,跳转到登录页面


下一篇:Sublime Text Build 3065 License key