The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.html
Example:ide
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
Note:spa
Sum(ABCD)=Sum(OD)−Sum(OB)−Sum(OC)+Sum(OA)code
ps: 注意dp的遞推公式htm
1 class NumMatrix { 2 public: 3 vector<vector<int>> dp; 4 5 NumMatrix(vector<vector<int>> matrix) { 6 int n =matrix.size(); 7 int m = n==0?0:matrix[0].size(); 8 9 10 dp = vector<vector<int>>(n+1,vector<int>(m+1,0)); 11 for(int i = 0 ;i<n;i++) 12 for(int j = 0;j<m;j++){ 13 dp[i+1][j+1] = dp[i][j+1]+dp[i+1][j]-dp[i][j]+matrix[i][j]; 14 } 15 } 16 17 int sumRegion(int rows1, int cols1, int rows2, int cols2) { 18 return dp[rows2+1][cols2+1] - dp[rows1][cols2+1] - dp[rows2+1][cols1] +dp[rows1][cols1]; 19 } 20 }; 21 22 /** 23 * Your NumMatrix object will be instantiated and called as such: 24 * NumMatrix obj = new NumMatrix(matrix); 25 * int param_1 = obj.sumRegion(row1,col1,row2,col2); 26 */