思路就是前缀和同一起点,加加减减。如上图,求红色小框的和,只需要让大绿框的和减去黄色和蓝色的和,因为多减去了粉色框的和,所以再加上就好了。
public class NumMatrix {
private int[][] preSum;
public NumMatrix(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return;
}
preSum = new int[matrix.length + 1][matrix[0].length + 1];//preSum[i][j]记录[0,0]->[i-1,j-1]的元素和
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {//构造前缀和preSum矩阵
preSum[i + 1][j + 1] = preSum[i + 1][j] + preSum[i][j + 1] - preSum[i][j] + matrix[i][j];
}
}
for (int i = 0; i < preSum.length; i++) {//输出preSum矩阵结果
for (int j = 0; j < preSum[0].length; j++) {
System.out.print(preSum[i][j] + " ");
}
System.out.println();
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {//目标矩阵之和由四个相邻矩阵运算得到
return preSum[row2 + 1][col2 + 1] - preSum[row1][col2 + 1] - preSum[row2 + 1][col1] + preSum[row1][col1];
}
}