# Jump game

Posted by chunyang on April 24, 2019

### 爬楼梯

F(n) = F(n-1) + F(n-2)

### Jump Game I

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.

class Solution {
public:
bool canJump(vector<int>& nums) {
int max_end = 0;
int length = nums.size();
for (int i = 0; i < length; ++i) {
// cout << "max_end: " << max_end << endl;

// if (i < max_end && nums[i] == 0) continue;

if(i > max_end) return false;
max_end = max(max_end, i + nums[i]);

if (max_end >= length - 1) return true;
}
return false;
}
};


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

Example:

Input: [2,3,1,1,4]

Output: 2

Explanation: 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.

Note:

You can assume that you can always reach the last index.

class Solution {
public:
int jump(vector<int>& nums) {
int cur_max_end = 0;
int next_max_end = 0;
int length = nums.size();
if (length < 2) return 0;
int count = 0;
for (int i = 0; i < length; ++i) {
// cout << "cur_max_end: " << cur_max_end << endl;

// cout << "next_max_end: " << next_max_end << endl;

if (cur_max_end == 0) {
cur_max_end = i + nums[i];
next_max_end = cur_max_end;
++count;
if (next_max_end >= length - 1) return count;
} else if (i <= cur_max_end) {
auto tmp = i + nums[i];
if (tmp > next_max_end) {
next_max_end = tmp;
} else {
continue;
}
} else {
++count;
cur_max_end = next_max_end;
next_max_end = max(next_max_end, i + nums[i]);
}
if (next_max_end >= length - 1) break;

}
return count + 1;
}
};