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 };

 

posted @ 2018-07-01 19:10  Zzz...y  阅读(164)  评论(0编辑  收藏  举报