1. 程式人生 > >Greedy--Jump Game II (Hard)

Greedy--Jump Game II (Hard)

原題

  • Problem Description

    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.

  • Sample Input

    [2,3,1,1,4]

  • Sample Output

    2

解題思路:

貪心:

在當前位置,判斷可跳至的最遠位置之前的位置中,哪些位置是可以跳到最遠
然後選取可以跳至最遠的位置,更新為當前位置;
然後重複此過程,直至能夠跳至結尾。

貪心思路和Jump Game I 一樣,但I需要判斷的是能否到達終點,II則是直接尋找區域性的最大值(最優解),然後進行跳躍次數累加。

程式碼思路:

1、遍歷陣列,每次尋找可以到達的最遠位置,然後更新pre_max_index


2、當遍歷達到當前位置,則進行下一步跳躍,並更新current_max_index

程式碼:

#include <vector>
using namespace std;
class Solution {
public:
    int jump(vector<int>& nums) {
        if (nums.size() < 2)
            return 0;
        int current_max_index = nums[0] + 0;//當前位置->可達到的最遠的位置
        int pre_max_index = nums[0
] + 0;//通過遍歷->可達到的最遠的位置 int jump_min = 1;//跳躍的次數 for (int i = 1; i < nums.size(); i++){ if (current_max_index < i){ jump_min++; current_max_index = pre_max_index; } if (pre_max_index < nums[i] + i) pre_max_index = nums[i] + i; } return jump_min; } };