1. 程式人生 > >45. Jump Game II(跳躍遊戲II)

45. Jump Game II(跳躍遊戲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.)

問題分析
這個問題的要求很明確,給定一串數字,數字的值表示在這個位置可以直接到達的最大長度,我們要求的則是到達最後一個數字所需要的最小步數,問題看起來很簡單,但是從數字開頭到結尾可能有許多種不同的走法,我們怎麼找出最短的那條路徑呢?我們可以用一個變數step來記錄我們所走的步數,但是step什麼時候才要加1呢?我們可以採取這樣的思維,我們可以定義i從0到最後一個下標,i是依次加1遞增的,但是這其中必然有很多不必要走的步數,我們的step只在必須要走的步數才加1。我們可以定義lastable,currentable兩個變數。lastable表示從上一個記錄的位置可以到達的最大位置,如果i的值不大於該數值,則表示從last這個位置可以直接到達i的位置,step就不需要加1;如果i的值大於該數值,則表示從last到大不了該位置,這一步就是必須的,step就要加1。同時要更新laetble的值。而currentable記錄當前位置可以到達的最大位置,用以更新lastable的值。

程式碼展示

#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std; 

class Solution {
public:
    int jump(vector<int>& nums){
        int lastable=0, currentable = 0, step =0;
        int n=nums.size();
        for(int i=0;i<n;i++){
            if(i>lastable){              //如果下標i超過了上一次最大可以到的的位置,則步數就要加1 
step+=1; lastable = currentable; //並且要重新定義上一步可以達到的最大位置 } int a= nums[i]+i; //如果下標i沒有超過上一次可以達到的最大位置,則代表這一位置可以有上一個記錄的位置直接跳達 if(currentable<a){ currentable = a; //所以到這個位置步數可以省略,既不用加1 ,並且每次都要記錄此位置可以到達的最大位置 } } return currentable >= n - 1 ? step : 0; //如果最後可以到達,則返回所用步數。 } }; int main(){ int n; vector<int> nums; cout<<"輸入容器的長度:"; cin>>n; int num[n]; for(int i = 0;i<n;i++){ cin>>num[i]; nums.push_back(num[i]); } Solution solution; int result=solution.jump(nums); cout<<result<<endl; }

執行結果展示
這裡寫圖片描述