标签:
Very similar to Range Sum Query - Immutable, but we now need to compute a 2d accunulated-sum. In fact, if you work in computer vision, you may know a name for such an array --- Integral Image.
To solve this problem, Stefan has already posted a very elegant solution.
The code is copied here.
1 class NumMatrix { 2 public: 3 NumMatrix(vector<vector<int>> &matrix) { 4 accu = matrix; 5 for (int i = 0; i < matrix.size(); i++) 6 for (int j = 0; j < matrix[0].size(); j++) 7 accu[i][j] += a(i-1, j) + a(i, j-1) - a(i-1, j-1); 8 } 9 10 int sumRegion(int row1, int col1, int row2, int col2) { 11 return a(row2, col2) - a(row1-1, col2) - a(row2, col1-1) + a(row1-1, col1-1); 12 } 13 private: 14 vector<vector<int>> accu; 15 int a(int i, int j) { 16 return i >= 0 && j >= 0 ? accu[i][j] : 0; 17 } 18 }; 19 20 21 // Your NumMatrix object will be instantiated and called as such: 22 // NumMatrix numMatrix(matrix); 23 // numMatrix.sumRegion(0, 1, 2, 3); 24 // numMatrix.sumRegion(1, 2, 3, 4);
[LeetCode] Range Sum Query 2D - Immutable
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4960413.html