阅读量:0
一夜无解,痛苦,遂拜倒于灵神门下,妄做狂徒也!
灵神秒解如下:
class NumMatrix: #二维初始矩阵 def __init__(self, matrix: List[List[int]]): m=len(matrix) n=len(matrix[0]) #扩充一下,防止数组越界 sum=[[0]*(n+1) for _ in range(m+1)] for i in range(m): for j in range(n): sum[i+1][j+1]=sum[i+1][j]+sum[i][j+1]-sum[i][j]+matrix[i][j] self.sum=sum #子矩阵计算和 def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: return self.sum[row2+1][col2+1]-self.sum[row2+1][col1]-self.sum[row1][col2+1]+self.sum[row1][col1]