• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
p-boost-q
博客园    首页    新随笔    联系   管理    订阅  订阅
1074. 元素和为目标值的子矩阵数量

给出矩阵 matrix 和目标值 target,返回元素总和等于目标值的非空子矩阵的数量。

子矩阵 x1, y1, x2, y2 是满足 x1 <= x <= x2 且 y1 <= y <= y2 的所有单元 matrix[x][y] 的集合。

如果 (x1, y1, x2, y2) 和 (x1', y1', x2', y2') 两个子矩阵中部分坐标不同(如:x1 != x1'),那么这两个子矩阵也不同。

 

 解析:

class Solution {
public:
    int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
        int hangshu = matrix.size(), lieshu = matrix[0].size();
        int preSum[hangshu][lieshu];
        memset(preSum, 0, sizeof(preSum));
        int result = 0;
        for(int x = 0;x < hangshu;++x)
        {
            for(int y = 0;y < lieshu;++y)
            {
                if(x == 0 && y == 0)
                {
                    preSum[x][y] = matrix[x][y];
                    
                }
                if(x == 0 && y != 0)
                {
                    preSum[x][y] = matrix[x][y] +  preSum[x][y-1];
                   
                }
                if(x != 0 && y == 0)
                {
                    preSum[x][y] = matrix[x][y] +  preSum[x-1][y];
                    
                }
                if(x != 0 && y != 0)
                {
                    preSum[x][y] =  matrix[x][y] + preSum[x][y-1] + preSum[x-1][y] - preSum[x-1][y-1];
                }
                for(int i = 0;i <= x;++i) //这个位置要加=
                {
                    for(int j = 0;j <= y;++j)//这个位置要加=
                    {
                        int a = i && j ? preSum[i-1][j-1] : 0;
                        int b = i ? preSum[i-1][y] : 0;
                        int c = j ? preSum[x][j-1] : 0;
                        if((preSum[x][y]-b-c+a) == target)
                        {
                            result++;
                        }
                    }
                }
            }
        }
        return result;
    }
};

 

posted on 2022-08-30 21:23  p-boost-q  阅读(41)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3