标签:
Yes the accu* is not necessary :)
class NumMatrix { vector<vector<int>> dp; public: NumMatrix(vector<vector<int>> &matrix) { int h = matrix.size(); if(!h) return; int w = matrix[0].size(); vector<vector<int>> accuCols(h, vector<int>(w)); vector<vector<int>> accuRows(h, vector<int>(w)); // Accumulated Col sums for(int i = 0; i < w; i ++) { accuCols[0][i] = matrix[0][i]; for(int j = 1; j < h; j ++) { accuCols[j][i] = accuCols[j - 1][i] + matrix[j][i]; } } // Accumulated Row sums for(int j = 0; j < h; j ++) { accuRows[j][0] = matrix[j][0]; for(int i = 1; i < w; i ++) { accuRows[j][i] = accuRows[j][i - 1] + matrix[j][i]; } } dp.assign(h + 1, vector<int>(w + 1, 0)); for(int i = 0; i < h; i ++) for(int j = 0; j < w; j ++) { dp[i + 1][j + 1] = dp[i][j] + accuCols[i][j] + accuRows[i][j] - matrix[i][j]; } } int sumRegion(int row1, int col1, int row2, int col2) { int v = dp[row2 + 1][col2 + 1] - dp[row1][col1]; int u = dp[row1][col2 + 1] - dp[row1][col1]; int l = dp[row2 + 1][col1] - dp[row1][col1]; return v - u - l; } };
LeetCode "Range Sum Query 2D - Immutable"
标签:
原文地址:http://www.cnblogs.com/tonix/p/4963963.html