# 304. 二维区域和检索 - 矩阵不可变

# 题目

给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)

# 题解

# 前缀和

var NumMatrix = function(matrix) {
  const m = matrix.length;
  if (m > 0) {
    const n = matrix[0].length;
    this.sums = new Array(m).fill(0).map(() => new Array(n + 1).fill(0));
    for (let i = 0; i < m; i++) {
      for (let j = 0; j < n; j++) {
        this.sums[i][j + 1] = this.sums[i][j] + matrix[i][j];
      }
    }
  }
};

NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {
  let sum = 0;
  for (let i = row1; i <= row2; i++) {
    sum += this.sums[i][col2 + 1] - this.sums[i][col1];
  }
  return sum;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20