题目如下:

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. log() exp()函数

    1 对数函数表示法 import numpy as np import math print('输出自然底数e:',math.e) # np表示法 # np.log()是以e为底的自然对数 print ...

  2. Windows下对函数打桩,及Linux类似技术

    一个简单的桩实现类: #define JMPCODE_LENGTH 5 //x86 平坦内存模式下,绝对跳转指令长度 #define JMPCMD_LENGTH 1 //机械码0xe9长度 #defi ...

  3. 【MM系列】SAP 通过原材料找到成品的函数

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP 通过原材料找到成品的函数   ...

  4. 深入理解java:2.3.1. 并发编程concurrent包 之Atomic原子操作(循环CAS)

    java中,可能有一些场景,操作非常简单,但是容易存在并发问题,比如i++, 此时,如果依赖锁机制,可能带来性能损耗等问题, 于是,如何更加简单的实现原子性操作,就成为java中需要面对的一个问题. ...

  5. Redis为什么不能使用一主一从哨兵

    哨兵机制 识别挂掉的主节点 quorum(法定人数) 是判定主节点不能访问所需要的最少哨兵数量 执行失效备援perform a failover 其中一个哨兵需要被选为救援的领导,并被授权执行救援,而 ...

  6. linux工具之screen

    screen官方网址:http://www.gnu.org/software/screen/ 参考文章:http://man.linuxde.net/screen 简介 Screen是一款由GNU计划 ...

  7. Luogu p2456 二进制方程

    这是一道我也不知道我gu了多久的题目 (然鹅还有n多任务没有完成) 反正--我太难了 好了言归正传,题目链接 是一道校内测的题目(现在应该没有人没考了吧?) 思路的话,是神仙并查集√ 觉得虽然并查集很 ...

  8. GUI程序原理分析

    1,Qt 是一套跨平台的程序设计库,这套程序设计库主要用于 GUI 方面的程序设计开发,所以本系列博文主要是利用C++介绍 GUI 程序设计技术: 2,命令行应用程序: 1,命令行应用程序的特点(Co ...

  9. Codeforces 1262D Optimal Subsequences(BIT+二分)

    首先比较容易想到肯定是前k大的元素,那么我们可以先对其进行sort,如果数值一样返回下标小的(见题意),接下里处理的时候我们发现需要将一个元素下标插入到有序序列并且需要访问第几个元素是什么,那么我们可 ...

  10. 剑指offer-两个链表的第一个公共结点-链表-python

    题目描述 输入两个链表,找出它们的第一个公共结点.   class Solution: def FindFirstCommonNode(self, pHead1, pHead2): # write c ...