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'.

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

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

输入样例3: Input: matrix = [[904]], target = 0 输出样例3: Output: 0

数据范围

Constraints:

  • 1 <= matrix.length <= 100
  • 1 <= matrix[0].length <= 100
  • -1000 <= matrix[i] <= 1000
  • -10^8 <= target <= 10^8

题目分析

Prefix Sum 模板题

代码实现

class Solution {
public:
    int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
    const int m = matrix.size(), n = matrix[0].size();
    int res = 0; 

    vector <vector <int>> sums(m + 1, vector <int>(n + 1));

    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++)
            sums[i][j] = sums[i][j - 1] + sums[i - 1][j] - sums[i - 1][j - 1] + matrix[i - 1][j - 1];

    int temp = 0; 
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            for (int p = 1; p <= i; p++) {
                for (int q = 1; q <= j; q++) {
                    temp = sums[i][j] - sums[i][q - 1] - sums[p - 1][j] + sums[p - 1][q - 1];
                    if (temp == target) res++;
                }
            }
        }
    }
    return res;
    }
};
分类: PrefixSum

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用*标注

友情链接:Ctips' blog, Colza’s blog

站点状态:Status