跳跃游戏 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];
    }
};

动态规划:

dpi:表示到达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];
    }
};

贪心:

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

相关推荐
金銀銅鐵2 天前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏
金銀銅鐵3 天前
借助 Pygame 探索最大公约数的规律
python·数学·游戏
nujnewnehc7 天前
不会 py, 用 ai 写了个游戏辅助的感受
人工智能·游戏
jump_jump8 天前
为了重玩金庸群侠传,我研究了一下 Ruffle 怎么复活 Flash
游戏·rust·github
XIAOHEZIcode9 天前
Linux系统鼠标偏移常见原因以及修复方案
linux·运维·游戏
Aloys_Code10 天前
逆向一个被遗忘的DVD游戏格式:从DES加密到Rust模拟器
游戏·模拟器·retroarch·复古游戏·native32·sunplus·赤刃·钢铁风暴
金銀銅鐵10 天前
用 Python 实现 Take-Away 游戏
python·游戏
金銀銅鐵10 天前
用 Pygame 实现 15 puzzle
python·数学·游戏
两水先木示13 天前
【Unity3D】小游戏启动优化、发热优化、蒙皮网格优化
游戏
资源分享助手13 天前
杀戮尖塔2下载、Slay the Spire 2中文版、卡牌肉鸽游戏、杀戮尖塔2联机、杀戮尖塔2攻略
游戏