当前位置:网站首页>leetcode:6110. 网格图中递增路径的数目【dfs + cache】
leetcode:6110. 网格图中递增路径的数目【dfs + cache】
2022-07-04 12:52:00 【白速龙王的回眸】

分析
dfs记忆化搜索,记录当前点的位置(至少有一条路径),然后把问题扔给下一个能走到的点,加上dfs
搜索每个位置为起点,后面能组成递增路径的总个数
遍历不同起点,由此得到总路径数
ac code
class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
MOD = 10 ** 9 + 7
m, n = len(grid), len(grid[0])
# dfs + memory优雅
# 当点和上一个点固定,它能走的最大长度也就固定
@cache
def dfs(r, c, pre):
res = 1 # 最少也是当前这个点
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] > pre:
res += dfs(nr, nc, grid[nr][nc])
return res
ans = 0
# 遍历每个起点获得不同起点的最大值
for i in range(m):
for j in range(n):
ans += dfs(i, j, grid[i][j])
ans %= MOD
return ans
总结
经典二维递增路径数量统计了
类似题目有最长的递增路径,只需要把res += 改成res = max(…)即可
边栏推荐
- 10.(地图数据篇)离线地形数据处理(供Cesium使用)
- Understand chisel language thoroughly 11. Chisel project construction, operation and test (III) -- scalatest of chisel test
- Install and use MAC redis, connect to remote server redis
- Leetcode T47: 全排列II
- C# wpf 实现截屏框实时截屏功能
- gin集成支付宝支付
- Code hoof collection of wonderful secret place
- nowcoder重排链表
- Use of arouter
- vscode 常用插件汇总
猜你喜欢

gin集成支付宝支付

安装Mysql

sharding key type not supported

Oppo find N2 product form first exposure: supplement all short boards

Hardware Basics - diode Basics

吃透Chisel语言.06.Chisel基础(三)——寄存器和计数器

Yingshi Ruida rushes to the scientific and Technological Innovation Board: the annual revenue is 450million and the proposed fund-raising is 979million

Xcode 异常图片导致ipa包增大问题

10.(地图数据篇)离线地形数据处理(供Cesium使用)

Unity shader learning (3) try to draw a circle
随机推荐
LiveData
学内核之三:使用GDB跟踪内核调用链
R语言ggplot2可视化:gganimate包创建动画图(gif)、使用anim_save函数保存gif可视化动图
奇妙秘境 码蹄集
【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
Understand chisel language thoroughly 05. Chisel Foundation (II) -- combinational circuits and operators
海外游戏代投需要注意的
92.(cesium篇)cesium楼栋分层
Incremental ternary subsequence [greedy training]
Gorm data insertion (transfer)
基于PaddleX的智能零售柜商品识别
2022 practice questions and mock exams for the main principals of hazardous chemical business units
Can mortgage with housing exclude compulsory execution
Hardware Basics - diode Basics
LifeCycle
R语言使用lattice包中的bwplot函数可视化箱图(box plot)、par.settings参数自定义主题模式
去除重複字母[貪心+單調棧(用數組+len來維持單調序列)]
[R language data science]: cross validation and looking back
Understand chisel language thoroughly 04. Chisel Foundation (I) - signal type and constant
Understand chisel language thoroughly 08. Chisel Foundation (V) -- wire, REG and IO, and how to understand chisel generation hardware