题目要求
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
的跳跃到达。
我们进行以下操作:
向
prob_list[m]
中push:m.pos - 0.pos
,m.pos - 1.pos
,m.pos - 2.pos
…m.pos - (m-1).pos
从
prob_list[m]
中pop出一个值k,如果存在节点i
,使得m.pos - i.pos = k
成立,那么向prob_list[i]
中push:k-1
、k
和k+1
重复步骤2,直到
prob_list[m]
向量为空令m = m-1
若m不等于1,则回到步骤2。如果m等于1且
prob_list[m]
向量中存在数字