Frog Jump - leetcode 403号题目个人题解

这篇博客详细介绍了LeetCode 403题——Frog Jump的解题思路,包括利用动态规划的方法分析青蛙能否跳过河中的石头,并探讨了原算法的时间复杂度为O(n^2 * log(n)),提出了通过递归优化算法的方案。
摘要由CSDN通过智能技术生成

题目要求

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.

解题思路

我们假设这条河上有m+1块石头,每一块石头的id分别为0、1…m-1、m。
0号石头固定在第0单元,1号石头固定在第1单元(由题目的条件可以推断出)。
x块石头所在的单元,我们用x.pos来指示。例如0.pos为0,1.pos为1.
假设青蛙可以到达第m块石头。那么如果最后1步的跨度假设是k,那倒数第2步的跨度就是k+1,或者k,或者k-1。如果倒数第2步的跨度为k-1,那么我们根据规则就可以知道倒数第3步的跨度的可能取值。
如果这样回溯,最终能回溯到0号石头,并且从0号石头发出的跳跃跨度为1,说明青蛙可以实现跳跃。
我们可以使用一个向量组prob_list[],这个向量组里有向量0~m,分别储存x:m号石头可能通过跨度为x的跳跃到达。
我们进行以下操作:

  1. prob_list[m]中push:m.pos - 0.posm.pos - 1.posm.pos - 2.posm.pos - (m-1).pos

  2. prob_list[m]中pop出一个值k,如果存在节点i,使得m.pos - i.pos = k成立,那么向prob_list[i]中push:k-1kk+1

  3. 重复步骤2,直到prob_list[m]向量为空

  4. 令m = m-1

  5. 若m不等于1,则回到步骤2。如果m等于1且prob_list[m]向量中存在数字

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值