class NumMatrix:
def __init__(self, matrix):
"""
:type matrix: List[List[int]]
"""
if not matrix:
return None
r = len(matrix)
c = len(matrix[0])
self.dp = [[0] * (c + 1) for _ in range(r + 1)] # 多加一行一列0
for i in range(1, r + 1):
for j in range(1, c + 1):
self.dp[i][j] = self.dp[i - 1][j] + self.dp[i][j - 1] + matrix[i - 1][j - 1] - self.dp[i - 1][j - 1]
def sumRegion(self, row1, col1, row2, col2):
"""
:type row1: int
:type col1: int
:type row2: int
:type col2: int
:rtype: int
"""
row1, col1, row2, col2 = row1 + 1, col1 + 1, row2 + 1, col2 + 1
# 状态转移方程
return self.dp[row2][col2] - self.dp[row1 - 1][col2] - self.dp[row2][col1 - 1] + self.dp[row1 - 1][col1 - 1]