问题描述:
- 实现
NumMatrix
类:
NumMatrix(int[][] matrix)
给定整数矩阵 matrix
进行初始化。int sumRegion(int row1, int col1, int row2, int col2)
返回左上角 (row1, col1)
、右下角 (row2, col2)
的子矩阵的元素总和。
核心思路:
- 二维前缀和基础应用题。
- 建立二维前缀和数组的公式为:
f
(
i
,
j
)
=
f
(
i
−
1
,
j
)
+
f
(
i
,
j
−
1
)
−
f
(
i
−
1
,
j
−
1
)
+
matrix
[
i
]
[
j
]
f(i, j)=f(i-1, j)+f(i, j-1)-f(i-1, j-1)+\operatorname{matrix}[i][j]
f(i,j)=f(i−1,j)+f(i,j−1)−f(i−1,j−1)+matrix[i][j] - 根据前缀和数组确定区域内求和的公式为:
sumRegion
(
row
1
,
col
1
,
row
2
,
col
2
)
=
f
(
row
2
,
col
2
)
−
f
(
row
1
−
1
,
col
2
)
−
f
(
row
2
,
col
1
−
1
)
+
f
(
row
1
−
1
,
col
1
−
1
)
\text {sumRegion}\left(\operatorname{row}_{1}, \operatorname{col}_{1}, \operatorname{row}_{2}, \operatorname{col}_{2}\right) \\ =f\left(\operatorname{row}_{2}, \operatorname{col}_{2}\right)-f\left(\operatorname{row}_{1}-1, \operatorname{col}_{2}\right)\\ -f\left(\operatorname{row}_{2}, \operatorname{col}_{1}-1\right)+f\left(\operatorname{row}_{1}-1, \operatorname{col}_{1}-1\right)
sumRegion(row1,col1,row2,col2)=f(row2,col2)−f(row1−1,col2)−f(row2,col1−1)+f(row1−1,col1−1)
- 作图理解公式即可,推导也很容易。
代码实现:
class NumMatrix
{
private:
vector<vector<int>> sum;
public:
NumMatrix(vector<vector<int>>& matrix)
{
int m = matrix.size();
int n = matrix[0].size();
sum = vector<vector<int>>(m+1, vector<int>(n+1));
for(int i = 1; i <= m; ++i) for(int j = 1; j <= n; ++j)
{
sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + matrix[i-1][j-1];
}
}
int sumRegion(int row1, int col1, int row2, int col2)
{
return sum[row2+1][col2+1] - sum[row1][col2+1] - sum[row2+1][col1] + sum[row1][col1];
}
};