No.207&210 - LeetCode[55] Jump Game & [45] Jump Game II - 数组走到最后的最少步骤

本文探讨了LeetCode上Jump Game II与Jump Game问题的算法解决方案。首先介绍了使用动态规划解决Jump Game II的方法,但指出这种方法可能会导致超时。然后提出了一种改进方案,利用游标和广度优先搜索(BFS)来寻找从起始位置到终点的最短路径,显著提高了效率。此外,还讨论了Jump Game问题的解决策略,通过迭代更新可达范围来判断是否能到达终点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

纯dp会超时

/*
 * @lc app=leetcode id=45 lang=cpp
 *
 * [45] Jump Game II
 */

// @lc code=start
class Solution {
public:
    int jump(vector<int>& nums) {
        int N = nums.size();
        vector<int> dp(N,-1);
        for(int i=0;i<N;i++){
            dp[i] = i;
        }
        for(int i=0;i<N;i++){
            for(int j=i+1;j<min(N,i+1+nums[i]);j++){
                dp[j] = min(dp[j],dp[i]+1);
            }
        }
        return dp[N-1];
    }
};
// @lc code=end

像这种只往前走,求最短路径的,可以考虑游标+BFS:

/*
 * @lc app=leetcode id=45 lang=cpp
 *
 * [45] Jump Game II
 */

// @lc code=start
class Solution {
public:
    int jump(vector<int>& nums) {
        int N = nums.size();
        if(N <= 1) return 0;
        queue<pair<int,int>> q;
        q.push(make_pair(0,0)); // loc,level
        int cur = 1;            // cursor
        while(!q.empty()){
            int loc = q.front().first;
            int level = q.front().second;
            for(int i=cur;i<min(N,loc+1+nums[loc]);i++){
                q.push(make_pair(i,level+1));
                if(i == N-1){
                    return level+1;
                }
            }
            cur = min(N,loc+1+nums[loc]);
            q.pop();
        }
        return -1;
    }
};
// @lc code=end
/*
 * @lc app=leetcode id=55 lang=cpp
 *
 * [55] Jump Game
 */

// @lc code=start
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int N = nums.size();
        int cur = 0;
        int ans = 0;
        queue<int> q;
        q.push(0);
        while(!q.empty()){
            int now = q.front();
            for(int i=cur+1;i<=min(N-1,now+nums[now]);i++){
                q.push(i);
            }
            cur = max(cur,now + nums[now]);
            q.pop();
        }
        if(cur >= N-1) return true;
        return false; 
    }
};
// @lc code=end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值