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 

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.

303. Range Sum Query - Immutable 的变形,这题是2D数组,给左上角和右下角的点,这两点的行和列组成了一个矩形,求这个矩形里所有数字的和。

解法:DP, 建立一个二维数组dp,其中dp[i][j]表示累计区间(0, 0)到(i, j)这个矩形区间所有数字的和,求(r1, c1)到(r2, c2)的矩形区间和时,只需dp[r2][c2] - dp[r2][c1 - 1] - dp[r1 - 1][c2] + dp[r1 - 1][c1 - 1]即可。

Java:

private int[][] dp;

public NumMatrix(int[][] matrix) {
if( matrix == null
|| matrix.length == 0
|| matrix[0].length == 0 ){
return;
} int m = matrix.length;
int n = matrix[0].length; dp = new int[m + 1][n + 1];
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] -dp[i - 1][j - 1] + matrix[i - 1][j - 1] ;
}
}
} public int sumRegion(int row1, int col1, int row2, int col2) {
int iMin = Math.min(row1, row2);
int iMax = Math.max(row1, row2); int jMin = Math.min(col1, col2);
int jMax = Math.max(col1, col2); return dp[iMax + 1][jMax + 1] - dp[iMax + 1][jMin] - dp[iMin][jMax + 1] + dp[iMin][jMin];
}

Python:

class NumMatrix(object):
def __init__(self, matrix):
if matrix is None or not matrix:
return
n, m = len(matrix), len(matrix[0])
self.sums = [ [0 for j in xrange(m+1)] for i in xrange(n+1) ]
for i in xrange(1, n+1):
for j in xrange(1, m+1):
self.sums[i][j] = matrix[i-1][j-1] + self.sums[i][j-1] + self.sums[i-1][j] - self.sums[i-1][j-1] def sumRegion(self, row1, col1, row2, col2):
row1, col1, row2, col2 = row1+1, col1+1, row2+1, col2+1
return self.sums[row2][col2] - self.sums[row2][col1-1] - self.sums[row1-1][col2] + self.sums[row1-1][col1-1]

Python:  

# Time:  ctor:   O(m * n),
# lookup: O(1)
# Space: O(m * n) class NumMatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
if not matrix:
return m, n = len(matrix), len(matrix[0])
self.__sums = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)]
for i in xrange(1, m+1):
for j in xrange(1, n+1):
self.__sums[i][j] = self.__sums[i][j-1] + matrix[i-1][j-1]
for j in xrange(1, n+1):
for i in xrange(1, m+1):
self.__sums[i][j] += self.__sums[i-1][j] def sumRegion(self, row1, col1, row2, col2):
"""
sum of elements matrix[(row1,col1)..(row2,col2)], inclusive.
:type row1: int
:type col1: int
:type row2: int
:type col2: int
:rtype: int
"""
return self.__sums[row2+1][col2+1] - self.__sums[row2+1][col1] - \
self.__sums[row1][col2+1] + self.__sums[row1][col1] 

C++:

class NumMatrix {
private:
int row, col;
vector<vector<int>> sums;
public:
NumMatrix(vector<vector<int>> &matrix) {
row = matrix.size();
col = row>0 ? matrix[0].size() : 0;
sums = vector<vector<int>>(row+1, vector<int>(col+1, 0));
for(int i=1; i<=row; i++) {
for(int j=1; j<=col; j++) {
sums[i][j] = matrix[i-1][j-1] +
sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1] ;
}
}
} int sumRegion(int row1, int col1, int row2, int col2) {
return sums[row2+1][col2+1] - sums[row2+1][col1] - sums[row1][col2+1] + sums[row1][col1];
}
};

  

类似题目:

[LeetCode] 303. Range Sum Query - Immutable 区域和检索 - 不可变

All LeetCode Questions List 题目汇总

[LeetCode] 304. Range Sum Query 2D - Immutable 二维区域和检索 - 不可变的更多相关文章

  1. LeetCode 304. Range Sum Query 2D - Immutable 二维区域和检索 - 矩阵不可变(C++/Java)

    题目: Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper ...

  2. 304 Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

    给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2). 上图子矩阵左上角 (row1, col1) = (2, 1) ,右 ...

  3. [LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  4. [leetcode]304. Range Sum Query 2D - Immutable二维区间求和 - 不变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  5. [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  6. leetcode 304. Range Sum Query 2D - Immutable(递推)

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  7. LeetCode 304. Range Sum Query 2D – Immutable

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  8. 【刷题-LeetCode】304. Range Sum Query 2D - Immutable

    Range Sum Query 2D - Immutable Given a 2D matrix matrix, find the sum of the elements inside the rec ...

  9. 【LeetCode】304. Range Sum Query 2D - Immutable 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 预先求和 相似题目 参考资料 日期 题目地址:htt ...

随机推荐

  1. Kotlin异常与Java异常的区别及注解详解

    Kotlin异常与Java异常的区别: throw的Kotlin中是个表达式,这样我们可以将throw作为Elvis表达式[val test = aa ?: bb,这样的则为Elvis表达式,表示如果 ...

  2. Maven模块化搭建总结

    1.Maven插件在eclipse的安装 windows——>preferences——>Maven——>installations——>add——>installati ...

  3. django 进行语言的国际化及在后台进行中英文切换

    项目的部署地为: 中国大陆与美国东海岸, 两个地区的服务器数据不进行同步, 中国地区的服务器页面展示中文, 美国地区的服务器页面展示成英文, 项目后台使用python编程语言进行开发, 并结合djan ...

  4. modbus-poll和modbus-slave工具的学习使用——modbus协议功能码2的解析

    功能码2的功能是:读从机离散量输入信号的 ON/OFF 状态.可读取1-2000个连续的离散量输入状态,如果离散输入的数量个数不是8的整数倍,则用0填充最后数据字节的剩余位,功能码2的查询信息规定了要 ...

  5. 决策树——ID3

    参考网址:https://www.cnblogs.com/further-further-further/p/9429257.html ID3算法 最优决策树生成 -- coding: utf-8 - ...

  6. java之大文件分段上传、断点续传

    文件上传是最古老的互联网操作之一,20多年来几乎没有怎么变化,还是操作麻烦.缺乏交互.用户体验差. 一.前端代码 英国程序员Remy Sharp总结了这些新的接口 ,本文在他的基础之上,讨论在前端采用 ...

  7. WinDbg常用命令系列---清屏

    .cls (Clear Screen) .cls命令清除调试器命令窗口显示. .cls 环境: 模式 用户模式下,内核模式 目标 实时. 崩溃转储 平台 全部 清屏前 清屏后

  8. Python 04 Geany的安装和配置

    安装原文:https://www.cnblogs.com/wongyi/p/7832567.html 配置原文:https://jingyan.baidu.com/album/154b46311ed9 ...

  9. 原创:协同过滤之spark FP-Growth树应用示例

    上一篇博客中,详细介绍了UserCF和ItemCF,ItemCF,就是通过用户的历史兴趣,把两个物品关联起来,这两个物品,可以有很高的相似度,也可以没有联系,比如经典的沃尔玛的啤酒尿布案例.通过Ite ...

  10. presto集成kerberos以及访问集成了kerberos的hive集群

    1.创建主体 注: 192.168.0.230 为单节点集群 192.168.4.50为kdc服务器 192.168.0.9为客户端 1.1.Kdc服务器创建主体 # kadmin.local -q ...