链接:https://leetcode.com/problems/range-sum-query-2d-immutable/
思路
矩阵值不变,可以缓存部分和,以减少计算
Approach 1: Caching rows. cach[r][c]表示matrix[r][0]~matrix[r][c]总和
Approach 2: Caching matrix. cach[r][c]表示matrix[0][0]~matrix[r][c]总和
代码
// Approach 1
class NumMatrix {
private:
vector<vector<int>> cach;
public:
NumMatrix(vector<vector<int>>& matrix) {
int n = matrix.size();
if(!n) return;
int m = matrix[0].size();
cach = {n, vector<int>(m)};
for(int r = 0; r < n; r++) {
int prev = 0;
for(int c = 0; c < m; c++) {
prev += matrix[r][c];
cach[r][c] = prev;
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
int sum = 0;
for(int r = row1; r <= row2; r++) {
sum += cach[r][col2] - (col1 == 0 ? 0 : cach[r][col1-1]);
}
return sum;
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
*/
// Approach 2
class NumMatrix {
private:
vector<vector<int>> cach;
public:
NumMatrix(vector<vector<int>>& matrix) {
int n = matrix.size();
if(!n) return;
int m = matrix[0].size();
cach = {n, vector<int>(m)};
int prev = 0;
for(int r = 0; r < n; r++) {
for(int c = 0; c < m; c++) {
prev += matrix[r][c];
cach[r][c] = prev;
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
int top = row1 == 0 ? 0 : cach[row1-1][col2],
left = col1 == 0 ? 0 : cach[row1][col1-1],
top_left = (row1 == 0 || col1 == 0) ? 0 : cach[row1-1][col1-1];
return cach[row2][col2] - top - left + top_left;
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
*/