Given a2D matrix matrix, find thesumofthe elements inside the rectangle defined by its upper left corner (row1, col1) andlowerright corner (row2, col2).
Range Sum Query 2D
The above rectangle (withthe red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which containssum = 8.
這道題目本身比較簡單,不過稍微略顯繁瑣。對於其中的部分細節問題要特殊處理。
class NumMatrix {
public:
vector<vector<int>> myMatrix;
NumMatrix(vector<vector<int>> matrix) {
int n = matrix.size();
if(n <= 0){
return;
}
int m = matrix[0].size();
if(m <= 0){
return ;
}
for(int i = 0; i < n;i++){
myMatrix.push_back(matrix[i]);
}
myMatrix[0][0] = matrix[0][0];
//intial the first columfor(int i = 1;i < n; ++i){
myMatrix[i][0] = matrix[i][0] + myMatrix[i-1][0];
}
//initial the first rowfor(int i = 1;i < m; ++i){
myMatrix[0][i] = matrix[0][i] + myMatrix[0][i-1];
}
//dp & initial the sum matrixfor(int i = 1;i < n; ++i){
for(int j = 1;j < m; ++j){
myMatrix[i][j] = matrix[i][j] + myMatrix[i-1][j] + myMatrix[i][j-1] - myMatrix[i-1][j-1];
cout<<myMatrix[i][j]<<",";
}
cout<<endl;
}
return;
}
int sumRegion(int row1, int col1, int row2, int col2) {
if(row1 < 0 || row2 < 0 ||
col1 < 0 || col2 < 0){
return0;
}
if(myMatrix.size() <= 0 || myMatrix[0].size() <= 0){
return0;
}
int result = myMatrix[row2][col2];
if(row1 > 0){
result -= myMatrix[row1-1][col2];
}
if(col1 > 0){
result -= myMatrix[row2][col1-1];
}
if(row1 > 0 && col1 > 0){
result += myMatrix[row1-1][col1-1];
}
return result;
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
*/