1. 程式人生 > >LeetCode 45. Jump Game II|貪心演算法

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

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

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

演算法分析

這道題是困難的難度,但實際上也不太難,這道題有很多種解法,我的解法效率雖然不算很高,但是使用了單純的貪心演算法,容易理解,而且還可以把路徑儲存起來。
我這個演算法在於,每一次選擇下一個點時,會判斷選擇該點之後,是不是能夠跳的更加遠,這就需要有一個內部的迴圈進行判斷。判斷在目前位置到可到達的位置之間,選擇一個能夠讓我下一步跳的更遠的點。思想十分簡單,但因為有內部迴圈,所以效率會比起加入動態規劃演算法慢了許多,不過也可以通過。時間複雜度最好的是O(N),最差的不會超過O(N^2)。

int jump(vector<int>& nums) {
    if(nums.size()<2) return 0;
    int i = 0;
    int count = 0;
    while(i<nums.size()-1){
        count++;        
        if(i+nums[i]>=nums.size()-1) return count;
        int  j = 1;
        int best = 0;
        int max_jump= 0; 
        for( ; j <= nums[i] ; j++){
            if
(nums[i+j]+j>max_jump){ max_jump = nums[i+j]+j; best = j; } } i+=best; } return count; }