【leetcode】【剑指offer Ⅱ】013. 二维子矩阵的和

问题描述:

  • 实现 NumMatrix 类:
    • NumMatrix(int[][] matrix) 给定整数矩阵 matrix 进行初始化。
    • int sumRegion(int row1, int col1, int row2, int col2) 返回左上角 (row1, col1)、右下角 (row2, col2) 的子矩阵的元素总和。

核心思路:

  • 二维前缀和基础应用题。
    • 建立二维前缀和数组的公式为:
      f ( i , j ) = f ( i − 1 , j ) + f ( i , j − 1 ) − f ( i − 1 , j − 1 ) + matrix ⁡ [ i ] [ j ] f(i, j)=f(i-1, j)+f(i, j-1)-f(i-1, j-1)+\operatorname{matrix}[i][j] f(i,j)=f(i1,j)+f(i,j1)f(i1,j1)+matrix[i][j]
    • 根据前缀和数组确定区域内求和的公式为:
      sumRegion ( row ⁡ 1 , col ⁡ 1 , row ⁡ 2 , col ⁡ 2 ) = f ( row ⁡ 2 , col ⁡ 2 ) − f ( row ⁡ 1 − 1 , col ⁡ 2 ) − f ( row ⁡ 2 , col ⁡ 1 − 1 ) + f ( row ⁡ 1 − 1 , col ⁡ 1 − 1 ) \text {sumRegion}\left(\operatorname{row}_{1}, \operatorname{col}_{1}, \operatorname{row}_{2}, \operatorname{col}_{2}\right) \\ =f\left(\operatorname{row}_{2}, \operatorname{col}_{2}\right)-f\left(\operatorname{row}_{1}-1, \operatorname{col}_{2}\right)\\ -f\left(\operatorname{row}_{2}, \operatorname{col}_{1}-1\right)+f\left(\operatorname{row}_{1}-1, \operatorname{col}_{1}-1\right) sumRegion(row1,col1,row2,col2)=f(row2,col2)f(row11,col2)f(row2,col11)+f(row11,col11)
  • 作图理解公式即可,推导也很容易。

代码实现:

class NumMatrix
{
private:
    vector<vector<int>> sum; // 二维前缀和数组
public:
    NumMatrix(vector<vector<int>>& matrix)
    {
        int m = matrix.size();
        int n = matrix[0].size();
        sum = vector<vector<int>>(m+1, vector<int>(n+1));
        for(int i = 1; i <= m; ++i) for(int j = 1; j <= n; ++j)
        {
            sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + matrix[i-1][j-1];
        }
    }
    
    int sumRegion(int row1, int col1, int row2, int col2)
    {
        return sum[row2+1][col2+1] - sum[row1][col2+1] - sum[row2+1][col1] + sum[row1][col1];
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值