当前位置:网站首页>LeetCode 403. 青蛙过河 每日一题
LeetCode 403. 青蛙过河 每日一题
2022-07-07 15:32:00 【@小红花】
问题描述
一只青蛙想要过河。 假定河流被等分为若干个单元格,并且在每一个单元格内都有可能放有一块石子(也有可能没有)。 青蛙可以跳上石子,但是不可以跳入水中。
给你石子的位置列表 stones(用单元格序号 升序 表示), 请判定青蛙能否成功过河(即能否在最后一步跳至最后一块石子上)。开始时, 青蛙默认已站在第一块石子上,并可以假定它第一步只能跳跃 1 个单位(即只能从单元格 1 跳至单元格 2 )。
如果青蛙上一步跳跃了 k 个单位,那么它接下来的跳跃距离只能选择为 k - 1、k 或 k + 1 个单位。 另请注意,青蛙只能向前方(终点的方向)跳跃。
示例 1:
输入:stones = [0,1,3,5,6,8,12,17]
输出:true
解释:青蛙可以成功过河,按照如下方案跳跃:跳 1 个单位到第 2 块石子, 然后跳 2 个单位到第 3 块石子, 接着 跳 2 个单位到第 4 块石子, 然后跳 3 个单位到第 6 块石子, 跳 4 个单位到第 7 块石子, 最后,跳 5 个单位到第 8 个石子(即最后一块石子)。
示例 2:输入:stones = [0,1,2,3,4,8,9,11]
输出:false
解释:这是因为第 5 和第 6 个石子之间的间距太大,没有可选的方案供青蛙跳跃过去。
提示:
2 <= stones.length <= 2000
0 <= stones[i] <= 231 - 1
stones[0] == 0
stones 按严格升序排列来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/frog-jump
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public boolean canCross(int[] stones) {
int n = stones.length;
boolean[][] dp = new boolean[n + 1][n + 1];
dp[0][0] = true;
for(int i = 1;i < n;i++){
for(int j = 0;j < i;j++){
//从第j颗石头到第i颗石头的步长要求最低是k
int k = stones[i] - stones[j];
//第j块石头的步长最大是j + 1
if(k <= j + 1){
//能否以步长为k的速度到达第i块石头
dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1];
}
}
}
for(int i = 1;i <= n;i++){
if(dp[n - 1][i]) return true;
}
return false;
}
}边栏推荐
猜你喜欢

Prediction - Grey Prediction

水平垂直居中 方法 和兼容

Talk about the realization of authority control and transaction record function of SAP system

"The" "PIP" "entry cannot be recognized as the name of a cmdlet, function, script file, or runnable program."
最新高频Android面试题目分享,带你一起探究Android事件分发机制

The difference and working principle between compiler and interpreter

Imitate the choice of enterprise wechat conference room

Tragedy caused by deleting the console statement

字节跳动Android面试,知识点总结+面试题解析

低代码(lowcode)帮助运输公司增强供应链管理的4种方式
随机推荐
laravel怎么获取到public路径
PHP has its own filtering and escape functions
typescript ts基础知识之tsconfig.json配置选项
The latest interview experience of Android manufacturers in 2022, Android view+handler+binder
OpenGL personal notes
数据中台落地实施之法
Talk about the realization of authority control and transaction record function of SAP system
Sort out several important Android knowledge and advanced Android development interview questions
logback. XML configure logs of different levels and set color output
【DesignMode】享元模式(Flyweight Pattern)
Personal notes of graphics (3)
最新高频Android面试题目分享,带你一起探究Android事件分发机制
laravel构造函数和中间件执行顺序问题
Inner monologue of accidental promotion
Detailed explanation of several ideas for implementing timed tasks in PHP
华东师大团队提出,具有DNA调控电路的卷积神经网络的系统分子实现
null == undefined
Temperature sensor chip used in temperature detector
Build an all in one application development platform, light flow, and establish a code free industry benchmark
Laravel5.1 Routing - routing packets