LeetCode - jump game II

本文详细解析了LeetCode上的Jump Game II问题,通过三种不同的算法——动态规划(超时)、广度优先搜索和贪心算法来解决该问题,并提供了相应的代码实现。

LeetCode - jump game II

1.题目描述

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.)
题目无法理解的看上一篇博客—–jump game I


2.思路阐述

1. DP:(TLE -time limited exceeded)
  • 设状态为 f[i],表示从第 0 层出发,走到 A[i] 时用的最小步数,则状态转移方程为:
    f(i) = 0, i==0
    f (i) = min {f(j)+i-j} , i>0时 j为可以直接跳到i的位置,即A[j] >= i-j i >j.
    时间复杂度O(n^2)

  • maxPos(i):走i步最远的位置

2. BFS-O(n)

[2 3 1 1 4] 初始,push 2, 第一步 push A[0+1] , A[0+2] ; delete 2
jump++;
第二步, jump++; push 4, 完成。
minJump =2;

可以看成处理最短路径问题。
每两个相隔点都有边长为1的边,同时,A[i]表示从i 到i+1, ….., i+A[i]存在一条边
所以代码相通的,可以多思考一下之间的关系

3. 贪心-O(n)

Let’s say the range of the current jump is [curBegin, curEnd], curFarthest is the farthest point that all points in [curBegin, curEnd] can reach. Once the current point reaches curEnd, then trigger another jump, and set the new curEnd with curFarthest, then keep the above steps, as the following:


3.代码实现

1. dp
//最丑陋的dp
class Solution {
    public :
    int jump(vector<int> nums) {
        int n = nums.size();
        int*f = new int[n];
        for(int i = 0; i < n; i++) {
            f[i] = 2000;  //初始化f[i]。 
        }
        f[0]= 0;  //f(i)表示 到i的最小步数。

        for(int i = 0; i< n; i++) {
            for(int j = 0; j< i; j++) {
                if(nums[j] >= i-j) {
                    if(f[j]+1 < f[i]) f[i] =f[j]+1;
                }
            } 

        }
        for(int i = 0; i < n; i++) {
            cout<<f[i]<<" "; 
        }
        cout << endl;
        return f[n-1]; 
    }
};
2. BFS
int jump(int A[], int n) {
     if(n<2)return 0;
     int level=0,currentMax=0,i=0,nextMax=0;

     while(currentMax-i+1>0){       //nodes count of current level>0
         level++;
         for(;i<=currentMax;i++){   //traverse current level , and update the max reach of next level
            nextMax=max(nextMax,A[i]+i);
            if(nextMax>=n-1)return level;   // if last element is in level+1,  then the min jump=level 
         }
         currentMax=nextMax;
     }
     return 0;
 }
3. 贪心
public int jump(int[] A) {
    int jumps = 0, curEnd = 0, curFarthest = 0;
    for (int i = 0; i < A.length - 1; i++) {
        curFarthest = Math.max(curFarthest, i + A[i]);
        if (i == curEnd) {
            jumps++;
            curEnd = curFarthest;
        }
    }
    return jumps;
}

没事多看代码理解。保证贴的代码对应的算法是对应的,不会说贪心的贴了dp的代码。还是要多看多理解。

你提供的代码是 **LeetCode 第55题:跳跃游戏(Jump Game)** 的标准贪心算法解法。该算法通过维护一个变量 `rightmost` 来记录当前能够到达的最远位置,从而判断是否可以跳到最后一个下标。 --- ## ✅ 代码解析与完整 VS2022 可运行版本 以下是适合在 **Visual Studio 2022 (VS2022)** 中运行的完整代码版本,包含 `vector`、主函数和测试用例。 ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: bool canJump(vector<int>& nums) { int n = nums.size(); int rightmost = 0; for (int i = 0; i < n; ++i) { if (i <= rightmost) { // 如果当前位置i是可以到达的 rightmost = max(rightmost, i + nums[i]); // 更新最远可达位置 if (rightmost >= n - 1) { return true; // 已能到达或超过终点 } } } return false; // 循环结束仍未到达终点 } }; // 主函数测试 int main() { Solution sol; vector<int> nums; // 测试用例 1 nums = {2, 3, 1, 1, 4}; cout << "输入数组: "; for (int num : nums) cout << num << " "; cout << "\n能否跳到最后?" << (sol.canJump(nums) ? "true" : "false") << endl << endl; // 测试用例 2 nums = {3, 2, 1, 0, 4}; cout << "输入数组: "; for (int num : nums) cout << num << " "; cout << "\n能否跳到最后?" << (sol.canJump(nums) ? "true" : "false") << endl << endl; // 测试用例 3 nums = {0}; cout << "输入数组: "; for (int num : nums) cout << num << " "; cout << "\n能否跳到最后?" << (sol.canJump(nums) ? "true" : "false") << endl << endl; // 测试用例 4 nums = {1, 0, 2}; cout << "输入数组: "; for (int num : nums) cout << num << " "; cout << "\n能否跳到最后?" << (sol.canJump(nums) ? "true" : "false") << endl << endl; return 0; } ``` --- ## ✅ 示例输出 ``` 输入数组: 2 3 1 1 4 能否跳到最后?true 输入数组: 3 2 1 0 4 能否跳到最后?false 输入数组: 0 能否跳到最后?true 输入数组: 1 0 2 能否跳到最后?false ``` --- ## ✅ 算法逻辑详解 ### ✅ 问题背景 给定一个非负整数数组 `nums`,你最初位于数组的第一个下标。每个下标 `i` 对应一个非负整数 `nums[i]`,表示你可以跳跃的最大步数。你的任务是判断是否可以从第一个下标跳到最后一个下标。 ### ✅ 解法思路:贪心算法(Greedy) #### 核心思想: - 维护一个变量 `rightmost`,表示当前能够到达的最远下标。 - 遍历数组: - 如果当前位置 `i` 在 `rightmost` 范围内,说明可以到达; - 更新 `rightmost` 为 `max(rightmost, i + nums[i])`; - 如果 `rightmost >= n - 1`,说明可以到达终点,直接返回 `true`; - 如果遍历结束后仍未到达终点,返回 `false`。 --- ## ✅ 时间与空间复杂度 | 类型 | 复杂度 | 说明 | |------|--------|------| | 时间复杂度 | O(n) | 只遍历一次数组 | | 空间复杂度 | O(1) | 只使用常数级额外空间 | --- ## ✅ 常见问题排查(VS2022) 1. **编译错误** - 确保包含 `<vector>` 和 `<algorithm>` - 使用 `using namespace std;` 或加上 `std::` 前缀 2. **运行时错误** - 注意空数组处理(题目保证数组长度 ≥ 1) - 确保访问 `nums[i]` 不越界 3. **逻辑错误** - 初始 `rightmost` 为 0 是关键 - `if (i <= rightmost)` 是防止不可达点的判断条件 --- ## ✅ 对比其他解法 | 解法 | 时间复杂度 | 空间复杂度 | 特点 | |------|------------|------------|------| | 贪心算法(当前方法) | O(n) | O(1) | 最优解,推荐 | | 动态规划(从后往前) | O(n²) | O(n) | 思路清晰但效率低 | | BFS / DFS | O(n²) | O(n) | 可以解决问题,但不推荐 | | 递归+记忆化搜索 | O(n²) | O(n) | 适合拓展思路 | ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值