Leetcode 403. Frog Jump

本文深入探讨了在一系列石头上跳跃的游戏算法实现。通过动态规划方法,计算在每个石头上可能的跳跃步长,确保能够从一个石头跳到下一个。算法使用了映射和向量数据结构来跟踪每个石头的位置和可能的步长,最终判断是否能到达最后一个石头。

dp[i] = […]

表示在第i块stone上允许跳出的步伐大小

dp[i]计算:

遍历stone[1]…stone[i-1]

如果能从stone[k]跳到stone[i],则向dp[i]加入新的gap-1,gap,gap+1,注意<=0的数不添加。

最后检查dp[-1]的长度是否不为0

class Solution {
public:
    bool canCross(vector<int>& stones) {
        if (stones[1] != 1)
            return false;
        map<int, int> stone_idx;
        for (int i = 0; i < stones.size(); ++i)
            stone_idx[stones[i]] = i;
        vector<vector<int>> steps(stones.size());  //steps[i] = {a,b,c}表示在第i个stone上能跳出的步伐数
        steps[0] = {1};
        for (int i = 0; i < stones.size(); ++i) {
            for (int step : steps[i]) {
                
                int next_stone = stone_idx[stones[i] + step];
                if (next_stone == 0)
                    continue;
                vector<int> next_step = {step - 1, step, step + 1};
                for (auto n_s : next_step) {
                    if (n_s <= 0)
                        continue;
                    if (find(steps[next_stone].begin(), steps[next_stone].end(), n_s) == steps[next_stone].end()){
                        steps[next_stone].push_back(n_s);
                    }
                }
            }
        }
        return steps[steps.size()-1].size() > 0;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值