leetcode1074. Number of Submatrices That Sum to Target

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1074. Number of Submatrices That Sum to Target相关的知识,希望对你有一定的参考价值。

题目如下:

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

 



 

以上是关于leetcode1074. Number of Submatrices That Sum to Target的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Number of Islands

Leetcode 200. number of Islands

leetcode200 Number of Islands

[LeetCode] 1513. Number of Substrings With Only 1s

python 学习 leetcode ---number of island

Leetcode 200. Number of Islands