先求前缀和数组,再根据四个角坐标计算矩形内元素的和。
class NumMatrix {
private:
int sums[210][210];
public:
NumMatrix(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) return;
for (int i = 0; i < matrix.size(); ++ i)
for (int j = 0; j < matrix[0].size(); ++ j)
sums[i + 1][j + 1] = matrix[i][j] - sums[i][j] + sums[i + 1][j] + sums[i][j + 1];
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sums[row2 + 1][col2 + 1] - sums[row2 + 1][col1] - sums[row1][col2 + 1] + sums[row1][col1];
}
};