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

题目大意: 给定一个非负整数数组,每个数字代表其最大步长,求到达最后的 index 的最小步数。

解题思路

动态规划

dp[i] 表示到达 index = i 所需要的最小步数,则有转化方程:
dp[i] = min { dp[j]+1, .... } , 其中 0 <= j < i 且 nums[j] >= i - j;

代码如下:

class Solution {
public:
    int jump(vector<int>& nums) {
        // dp[i]: 到达 index = i 的位置的最小步数
        vector<int> dp;
        dp.resize(nums.size(), 0);

        for(int i = 0; i < nums.size()-1; ++i)
        {
            for(int j = 1; j <= nums[i]; ++j)
            {
                if(i+j < nums.size())
                {
                    if(dp[i+j] != 0) dp[i+j] = min(dp[i]+1, dp[i+j]);
                    else dp[i+j] = dp[i]+1;
                }
            }
        }

        return dp.back();
    }
};

很不幸,时间复杂度过高。 这个代码会 TLE

贪心

由于数组中给定的数字表示的是最大步长,因此,我们只需要记录每一步能到达的最远距离(maxDistance),以及下一步的可能最远距离(maxTouch),每次更新下一步可能的最大距离即可。

如图:
LeetCode: 45. Jump Game II_第1张图片

时间复杂度 O(n), 空间复杂度 O(1)

AC代码

class Solution {
public:
    int jump(vector<int>& nums) {

        int maxDistance = 0;     // 记录上一步走的最大距离
        int nMinStep    = 0;     // 记录最小的步数
        int maxTouch    = 0;     // 记录这一步能到达的最大距离

        for(int i = 0; i < nums.size(); ++i)
        {
            if(maxDistance >= nums.size()-1) break;

            // 当上一步没有到达 i 时, 就该走这一步了。
            if(maxDistance < i)
            {
                ++nMinStep;
                maxDistance = maxTouch;
            }

            // 在第 index = i 时, 能达到的距离
            maxTouch = max(maxTouch, i + nums[i]);
        }

        return nMinStep;
    }
};

你可能感兴趣的:(LeetCode,杨领well的,LeetCode,题解专栏)