题目:
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;
}
};