269、二维区域和检索 - 矩阵不可变
程序员文章站
2022-03-23 17:55:56
...
题目描述:
说明:
你可以假设矩阵不可变。
会多次调用 sumRegion 方法。
你可以假设 row1 ≤ row2 且 col1 ≤ col2。
emm使用dp
比较简单:
class NumMatrix {
int[][] dp = null;
public NumMatrix(int[][] matrix) {
int row = matrix.length;
if(row != 0){
int col = matrix[0].length;
if (row != 0 && col != 0) {
dp = new int[row][col];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < col; j++) {
if (j == 0) {
dp[i][j] = matrix[i][j];
continue;
}
dp[i][j] = dp[i][j - 1] + matrix[i][j];
}
}
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int tem = 0;
for (int i = row1; i <= row2; i++) {
if (col1 == 0) {
tem = tem + dp[i][col2];
continue;
}
tem = tem + dp[i][col2] - dp[i][col1 - 1];
}
return tem;
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
*/
下一篇: 电话号码的字母组合(Python)