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

### 跳跃游戏 II 的算法实现 跳跃游戏 II 是一道经典的贪心算法问题,目标是从数组的第一个位置跳到最后一个位置,并返回最少的跳跃次数。以下是基于 Go 语言的解决方案。 #### 算法思路 该问题可以通过维护当前能够覆盖的最大范围来解决。每次当遍历的位置达到上一次记录的最大边界时,更新最大边界并增加跳跃次数[^1]。这种方法的核心在于利用局部最优解(即每一步尽可能远地跳跃)来获得全局最优解。 #### 实现代码 (Go) ```go package main import ( "fmt" ) func jump(nums []int) int { if len(nums) <= 1 { return 0 } jumps := 0 // 记录跳跃次数 currentEnd := 0 // 当前区间的最右端 farthest := 0 // 可以到达的最远距离 for i := 0; i < len(nums)-1; i++ { // 更新能到达的最远距离 if nums[i]+i > farthest { farthest = nums[i] + i } // 到达当前区间边界时触发跳跃 if i == currentEnd { jumps++ currentEnd = farthest // 如果已经可以到达终点,则提前结束循环 if currentEnd >= len(nums)-1 { break } } } return jumps } func main() { nums := []int{2, 3, 1, 1, 4} // 测试数据 fmt.Println(jump(nums)) // 输出最小跳跃次数 } ``` 上述代码通过 `jumps` 来计数跳跃次数,`currentEnd` 表示当前步所能到达的最远索引,而 `farthest` 则表示下一步可能到达的最远索引。每当遍历到 `currentEnd` 时,就执行一次跳跃操作并将新的边界设置为 `farthest`。 #### 复杂度分析 - **时间复杂度**: O(n),其中 n 是输入数组的长度。因为只需要遍历整个数组一次。 - **空间复杂度**: O(1),仅使用了常量级额外存储空间。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值