跳跃游戏 II

跳跃游戏 II

思路:

想到用队列,一层一层往外扩。

相当于暴力了,还是过了,因为稍微剪了一点枝。

代码:

cpp 复制代码
class Solution {
public:
    int jump(vector<int>& nums) {
        int n=nums.size();
        queue<int> q;//<下标>
        unordered_map<int,int> m;//键值对:键:下标  值:最小次数
        q.push(0);
        m[0]=0;
        while(!q.empty())
        {
            auto t=q.front();
            q.pop();
            int zuiyuanjuli=t+nums[t];
            for (int i = t + 1; i <= zuiyuanjuli && i < n; i++) 
            {
                // 如果没有访问过或者找到了更少的跳跃次数
                if (m.find(i) == m.end() || m[t] + 1 < m[i]) 
                {
                    m[i] = m[t] + 1;
                    q.push(i); // 将新位置加入队列
                    // 如果已经到达终点
                    if (i == n - 1)
                     {
                        return m[i];
                    }
                }
            }
            
        }
        return m[n-1];
    }
};

动态规划:

dp[i]:表示到达i所需的最短次数。

cpp 复制代码
const int N = 1e4+10;
int dp[N];
class Solution {
public:
    int jump(vector<int>& nums) {
        memset(dp,0x3f,sizeof dp);
        dp[0]=0;
        for(int i=0;i<nums.size();i++)
        {
            int step=nums[i];
            for(int j=i+1;j<=i+step&&j<nums.size();j++)
            {
                dp[j]=min(dp[j],dp[i]+1);
            }
        }
        return dp[nums.size()-1];
    }
};

贪心:

觉得代码不咋好理解,好难啊。。。

相关推荐
摸鱼的春哥3 天前
10年3次大失败,他从“罪人”输成了中年人的“白月光”
游戏
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
2501_918126913 天前
用html5写一个flappybird游戏
css·游戏·html5
惊鸿.Jh4 天前
3227. 字符串元音游戏
游戏
wanhengidc5 天前
手机云服务是什么意思?
运维·网络·安全·游戏·智能手机
伐尘5 天前
【CE】图形化CE游戏教程通关手册
前端·chrome·游戏·逆向
脚踏实地,坚持不懈!6 天前
Android,Jetpack Compose,坦克大战游戏案例Demo
android·游戏
过河卒_zh15667666 天前
9.12AI简报丨腾讯投资AI游戏平台,B站开源AniSora V3
人工智能·算法·游戏·aigc·算法备案·生成合成类算法备案
wanhengidc6 天前
服务器内存不足会造成哪些影响?
运维·服务器·网络·游戏·智能手机
念念不忘 必有回响6 天前
Pygame模块化实战:从零构建Aliens射击游戏全流程(一)
python·游戏·pygame