leetcode(29)矩阵搜索系列题目
64. 最小路径和
动态规划
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
res = 0
dp = [[0]* n for _ in range(m)] #注意先列再行
dp[0][0] = grid[0][0]
for i in range(1, m):
dp[i][0] = dp[i - 1][0] + grid[i][0]
for j in range(1, n):
dp[0][j] = dp[0][j - 1] + grid[0][j]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
return dp[-1][-1]
6148. 矩阵中的局部最大值
本质上是在做最大池化
class Solution:
def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid[0])
res = [[1]*(n - 2) for _ in range(n-2)]
for i in range(n-2):
for j in range(n-2):
max_num = 1
for p in range(i, i+3):
for q in range(j, j+3):
max_num = max(max_num, grid[p][q])
res[i][j] = max_num
return res
另一种优化的方法,原地修改,不需要使用一个新矩阵来返回
class Solution:
def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid[0])
for i in range(n-2):
for j in range(n-2):
grid[i][j] = max(max(raw[j:j+3]) for raw in grid[i:i+3])
grid[i].pop() # 删除前面两列
grid[i].pop()
grid.pop() # 删除前面两行
grid.pop()
return grid