题目:
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
Given matrix = [ [3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5] ] sumRegion(2, 1, 4, 3) -> 8 sumRegion(1, 1, 2, 2) -> 11 sumRegion(1, 2, 2, 4) -> 12题目解析:
在本题中要运用动态规划的方法来解决比较方便。我们首先用vector<vector<int>> sum来记录在i行,j列内部的数值之和。经过画图可以很容易的得到这样一个关系式:sum[i][j]=matrix[i-1][j-1]+sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1];这就是我在本题中解决问题地基础。当我们要求特定地行列之间地数值之和时,我们可以这样计算:sum[row2+1][col2+1] - sum[row2+1][col1] - sum[row1][col2+1] + sum[row1][col1];,其中col以及row是自己设置的特定行列。以上关系式可以很容易的通过画图得知。我就不赘述了。详细实现方法见代码。
代码:
class NumMatrix { public:
NumMatrix(vector<vector<int>> matrix) { int a=matrix.size(); int b=a>0 ? matrix[0].size() : 0; if(a==0) return; sum = vector<vector<int>>(a+1, vector<int>(b+1, 0)); for(int i=1;i<a+1;i++) { for(int j=1;j<b+1;j++) { sum[i][j]=matrix[i-1][j-1]+sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]; } } } int sumRegion(int row1, int col1, int row2, int col2) { int s=sum[row2+1][col2+1] - sum[row2+1][col1] - sum[row1][col2+1] + sum[row1][col1]; return s; } };vector<vector<int>> sum;