45. Jump Game II

Posted zzz-y

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了45. 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.

从起点跳到终点,求最小的跳跃次数,在 i 处能跳的最远距离是 nums[i]。

 

假如当前位于 i ,能跳跃的最大距离是 nums[i],对于每一个 j ∈ [i + 1, i + nums[i] ],通过这个点能达到的最远距离是 j + nums[j] 。那么最佳跳板就是 j 

 1 class Solution {
 2 public:
 3     int jump(vector<int>& nums) {
 4         int i = 0;
 5         int cnt = 0;
 6         int len = nums.size();
 7         while (i < len - 1) {
 8             if (i + nums[i] >= len - 1)
 9                 return cnt + 1;
10             int key = i + 1;
11             for (int j = i + 2; j <= i + nums[i]; ++j) {
12                 if (j + nums[j] > key + nums[key])
13                     key = j;
14             }
15             i = key;
16             ++cnt;
17         }
18         return cnt;
19     }
20 };

 

以上是关于45. Jump Game II的主要内容,如果未能解决你的问题,请参考以下文章

45. Jump Game II

55. 45. Jump Game II *HARD*

45. Jump Game II

45. Jump Game II

45. Jump Game II

45. Jump Game II