1. 题目
2. 解题
dp[i][j]数组表示 从左上角到i,j
位置的所有和
class NumMatrix {
vector<vector<int>> sum;
public:
NumMatrix(vector<vector<int>>& matrix) {
if(matrix.empty())
return;
int r = matrix.size(), c = matrix[0].size(), i, j;
sum = vector<vector<int>> (r 1, vector<int>(c 1, 0));
for(i = 0; i < r; i )
{
for(j = 0; j < c; j )
{
sum[i 1][j 1] = sum[i 1][j] sum[i][j 1] matrix[i][j]-sum[i][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if(sum.empty())
return 0;
return sum[row2 1][col2 1] - sum[row1][col2 1] - sum[row2 1][col1] sum[row1][col1];
}
};
or 按行dp
代码语言:javascript复制class NumMatrix {
vector<vector<int>> sumofrows;
public:
NumMatrix(vector<vector<int>>& matrix) {
if(matrix.empty())
return;
int r = matrix.size(), c = matrix[0].size(), i, j, sum = 0;
vector<int> temp(c,0);
for(i = 0; i < r; i )
{
sum = 0;
for(j = 0; j < c; j )
{
sum = matrix[i][j];
temp[j] = sum;
}
sumofrows.push_back(temp);
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if(sumofrows.empty())
return 0;
int i, j, sum = 0;
if(col1 != 0)
for(i = row1; i <= row2; i )
{
sum = sumofrows[i][col2]-sumofrows[i][col1-1];
}
else
for(i = row1; i <= row2; i )
{
sum = sumofrows[i][col2];
}
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);
*/