题目如下:

Given a matrix, and a target, return the number of non-empty submatrices that sum to target.

A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.

Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.

Example 1:

Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.

Example 2:

Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.

Note:

  1. 1 <= matrix.length <= 300
  2. 1 <= matrix[0].length <= 300
  3. -1000 <= matrix[i] <= 1000
  4. -10^8 <= target <= 10^8

解题思路:暴力计算的方法时间复杂度是O(n^4),而matrix.length最大值是300,应该无法被AC。那O(n^3)可以吗?试试吧。首先引入一个二维数组val_grid , 记var_grid[m][n] 为从0开始到第m行这个区间内第n列的值的和,例如用例1中的输入[[0,1,0],[1,1,1],[0,1,0]],其对应的val_grid为[[0, 1, 0], [1, 2, 1], [1, 3, 1]] 。如果要计算matrix中第j行~第i行区间内有多少满足和等于target的子矩阵,很轻松就可以求出这个子矩阵每一列的和,例如第k的列的和为 val_grid[i][k] - val_grid[j-1][k] (j>0),接下来令k in range(0,len(matrix[0]),依次判断[j~i]每一列的和是否等于target,同时累加并记录从0开始的列和,假设[0~k]累计的列和是sum,只要判断历史的列和中有多少个满足 sum - target,即可求出[j~i]子矩阵里面以k列为右边列的满足条件的子矩阵个数。这样即可将复杂度优化成O(n^3)。

代码如下:

class Solution(object):
def numSubmatrixSumTarget(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: int
"""
val_grid = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
for j in range(len(matrix[0])):
amount = 0
for i in range(len(matrix)):
amount += matrix[i][j]
val_grid[i][j] = amount
#print val_grid res = 0
for i in range(len(matrix)):
for j in range(i+1):
dic = {}
amount = 0
for k in range(len(matrix[i])):
v = val_grid[i][k]
if j > 0:
v -= val_grid[j-1][k]
amount += v
if amount == target:res += 1
if amount - target in dic:
res += dic[amount - target]
dic[amount] = dic.setdefault(amount,0) + 1
return res

【leetcode】1074. Number of Submatrices That Sum to Target的更多相关文章

  1. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  2. 【LeetCode】792. Number of Matching Subsequences 解题报告(Python)

    [LeetCode]792. Number of Matching Subsequences 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  3. 【LeetCode】673. Number of Longest Increasing Subsequence 解题报告(Python)

    [LeetCode]673. Number of Longest Increasing Subsequence 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https:/ ...

  4. 【leetcode】698. Partition to K Equal Sum Subsets

    题目如下: 解题思路:本题是[leetcode]473. Matchsticks to Square的姊妹篇,唯一的区别是[leetcode]473. Matchsticks to Square指定了 ...

  5. 【LeetCode】Single Number I & II & III

    Single Number I : Given an array of integers, every element appears twice except for one. Find that ...

  6. 【LeetCode】698. Partition to K Equal Sum Subsets 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 日期 题目地址:https://leetco ...

  7. 【LeetCode】476. Number Complement (java实现)

    原题链接 https://leetcode.com/problems/number-complement/ 原题 Given a positive integer, output its comple ...

  8. 【LeetCode】191. Number of 1 Bits 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 右移32次 计算末尾的1的个数 转成二进制统计1的个 ...

  9. 【LeetCode】1128. Number of Equivalent Domino Pairs 等价多米诺骨牌对的数量(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典统计 代码 复杂度分析 日期 题目地址:http ...

随机推荐

  1. Struts2测试题

    今天给大家看一套我最近做的一套关于Struts2的题: 1.以下关于jQuery说法错误的选项是( D ). A.“$”为jQuery脚本库的默认全局变量名,即“$” = “jQuery” B.$.a ...

  2. 《Using Databases with Python》Week3 Data Models and Relational SQL 课堂笔记

    Coursera课程<Using Databases with Python> 密歇根大学 Week3 Data Models and Relational SQL 15.4 Design ...

  3. 【Hibernate】---【注解】一对多

    一.核心配置文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-con ...

  4. 6.824 Lab 2: Raft 2A

    6.824 Lab 2: Raft Part 2A Due: Feb 23 at 11:59pm Part 2B Due: Mar 2 at 11:59pm Part 2C Due: Mar 9 at ...

  5. 创建React脚手架

    node版本10.14.2 下载地址 如果是其版本的话会出错 css-loader 会不兼容 主要是8.x的版本不兼容 npm install -g create-react-app 全局安装 cre ...

  6. HashMap中确定数组位置为什么要用hash进行扰动

    HashMap数据存储的过程先根据key获得hash值,通过 (n - 1) & hash 判断当前元素存放的位置(这里的 n 指的是数组的长度),如果当前位置存在元素的话,就判断该元素与要存 ...

  7. UUID工具类及使用

    1.工具类: package UUIdtest; import java.util.UUID; public class UUIDUtil { public static String getUUID ...

  8. Qfile

    打开方式: void AddStudents::write_to_file(QString src){ QFile file("stu.txt"); if (!file.open( ...

  9. Python虚拟环境命令

    cd D:\virtual\ virtualenv -p D\Python35\python.exe env1 cd env1 cd Scripts activate.bat # 激活该虚拟环境 de ...

  10. 一张图说明移动前端开发与web前端开发的区别