Range Sum Query 2D - Immutable
牛人的代码,备忘学习一下
class NumMatrix {
public:
vector<vector<int>> dp;
int n, m;
NumMatrix(vector<vector<int>> matrix) {
n = matrix.size();
if(n > 0 && (m = matrix[0].size()) > 0) {
dp.resize(n);
for(int i=0; i<n; i++)
dp[i].resize(m);
dp[0][0] = matrix[0][0];
int sum = matrix[0][0];
for(int i=1; i<n; i++)
dp[i][0] = matrix[i][0] + dp[i-1][0];
for(int j=1; j<m; j++)
dp[0][j] = matrix[0][j] + dp[0][j-1];
for(int i=1; i<n; i++) {
for(int j=1; j<m; j++) {
dp[i][j] = matrix[i][j] + dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1];
}
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if(n == 0 || m == 0)
return 0;
if(row1 == 0 && col1 == 0) {
return dp[row2][col2];
}
else if(row1 == 0 && col1 > 0) {
return dp[row2][col2] - dp[row2][col1-1];
}
else if(row1 > 0 && col1 == 0) {
return dp[row2][col2] - dp[row1-1][col2];
}
else {
return dp[row2][col2] - dp[row1-1][col2] - dp[row2][col1-1] + dp[row1-1][col1-1];
}
}
};