Leetcode (403) Frog Jump

  • 题目:

    A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

    Given a list of stones’ positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.

    If the frog’s last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.

    Note:

    • The number of stones is ≥ 2 and is < 1,100.
    • Each stone’s position will be a non-negative integer < 231.
    • The first stone’s position is always 0.
  • 题意:给定一个石头位置的序列,要求模拟一个青蛙跳的过程,青蛙一次跳跃的距离取决于它上一次跳跃的距离,若上一次距离为k,则下一次能够跳跃的距离只能是k-1,k,k+1三者之一。而青蛙首次从0号石头跳跃的距离只能为1。最后求解青蛙能否跳到最后一个石头上。

  • 思路:典型的动态规划问题,从一个石头转移到下一个石头上,而因为这里转移的距离有限制,因此,必须记录从哪个石头转移过来的,来保证下一次转移无误。记 dpij 表示第 i 个石头能从第 j 个石头转移过来,那次此时 i 能转移到下一个石头就是与 i 距离为 dist(i,j)1 , dist(i,j) dist(i,j)+1 的。
class Solution {
public:
    bool canCross(vector<int>& stones) {
        int size=stones.size();
        if (size == 2 && stones[1] > 1) return false;
        vector<vector<bool>> dp(size, vector<bool>(size, 0));
        dp[1][0] = true;
        for (int i=1;i<size;++i)
        {
            for (int j=0;j<i;++j)
            {
                if (dp[i][j])
                {
                    int k=i+1, dist=stones[i]-stones[j];
                    while (k<size && stones[k]<=stones[i]+dist+1)
                    {
                        if (abs(stones[k]-stones[i]-dist) <= 1)
                        {
                            dp[k][i] = true;
                        }
                        k++;
                    }
                }
            }
        }
        for (int i=0;i<size;++i)
        {
            if (dp[size-1][i] != 0) return true;
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值