• 23.4%

https://leetcode.com/problems/range-sum-query-2d-immutable/

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.

Note:

1. You may assume that the matrix does not change.
2. There are many calls to sumRegion function.
3. You may assume that row1 ≤ row2 and col1 ≤ col2.

#### cpp

https://discuss.leetcode.com/topic/29536/clean-c-solution-and-explaination-o-mn-space-with-o-1-time

Clean C++ Solution and Explaination - O(mn) space with O(1) time

Construct a 2D array sums[row+1][col+1]

(notice: we add additional blank row sums[0][col+1]={0} and blank column sums[row+1][0]={0} to remove the edge case checking), so, we can have the following definition

sums[i+1][j+1] represents the sum of area from matrix[0][0] to matrix[i][j]

To calculate sums, the ideas as below

So, we use the same idea to find the specific area’s sum.

And we can have the following code

https://discuss.leetcode.com/topic/29401/c-with-helper

C++ with helper

My accu[i][j] is the sum of matrix[0..i][0..j], and a(i, j) helps with edge cases.

Afterthought

I could use

which is shorter but I think less clear. I do like already using sumRegion in the precomputation, though.

my code:

#### python

https://discuss.leetcode.com/topic/29354/sharing-my-python-solution

Sharing My Python solution

The idea is simple, just precompute sums for all matrices with (0, 0) as top left corner and (i, j) as bottom right corner. There are O(n^2) of these matrices, so we store them in a 2D table. In order to make code simpler, I add an extra column and row, filled with 0.

#### java

https://discuss.leetcode.com/topic/29355/clean-and-easy-to-understand-java-solution

Clean and easy to understand java solution