暴力法:
private int[][] data;
public NumMatrix(int[][] matrix) {
data = matrix;
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int sum = 0;
for (int r = row1; r <= row2; r++) {
for (int c = col1; c <= col2; c++) {
sum += data[r][c];
}
}
return sum;
}
动规:
class NumMatrix {
private int[][] dp;
public NumMatrix(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return;
dp = new int[matrix.length][matrix[0].length + 1];
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[0].length; c++) {
dp[r][c + 1] = dp[r][c] + matrix[r][c];
}
}
}
将计算的过程分为两部分:
public int sumRegion(int row1, int col1, int row2, int col2) {
int sum = 0;
for (int row = row1; row <= row2; row++) {
sum += dp[row][col2 + 1] - dp[row][col1];
}
return sum;
}
}