45. 跳跃游戏 II

开始打算直接用递归来做,实现后发现超时了,代码如下:

int Min(int a, int b)
{
    return a > b ? b : a;
}
void jump_helper(vector<int>& nums, int start, int count, int &current_min)
{
    int length = nums.size();
    if (start >= length-1)
    {
        current_min = Min(current_min, count);
        return;
    }
    for (int steps = 1; steps <= nums[start]; steps++)
    {
        jump_helper(nums, start + steps, count + 1, current_min);
    }
}
int jump2(vector<int>& nums) {
    int length = nums.size();
    int count = 0;
    int min = INT_MAX;
    jump_helper(nums, 0, count, min);
    return min;
}

其实可以用贪婪法来做,找到可以到达最远的下一个点,作为更新的点,不停找下去,直到跳走。

需要考虑只有一个数为0的情况,此时return 0.

int Max(int a, int b)
{
    return a > b ? a : b;
}
int jump(vector<int>& nums) {
    int length = nums.size();
    int count = 0;
    if (length < 2)
        return 0;
    for (int pos = 0; pos < length  ; )
    {
        int next = pos;
        int current_pos = pos;

        for (int i = 0; i <= nums[pos]; i++)
        {
            if (pos + i >= nums.size() - 1)
                return ++count;
            if (pos + i + nums[pos + i]> next)
            {
                next = pos + i + nums[pos + i];
                current_pos = pos + i;
            }

        }
        pos = current_pos;
        count++;
    }
    return count;
}
原文地址:https://www.cnblogs.com/Oscar67/p/9285755.html