登录
OAmaster

You are given a 2d matrix A of m rows and n columns and you have to generate a matrix B of same dimension but the elements must be a summation of all the previous elements up to now. Function Description Complete the function generateMatrixB in the editor. generateMatrixB has the following parameter:

  • int[][] A: a 2D array of integers Returns int[][]: the generated matrix B

Example 1

Input:

A = [[1,2,3],[4,5,6]]

Output:

[[1,3,6],[5,12,21]]

Explanation: The elements of matrix B are calculated as follows:

  • B(0,0) = A(0,0) = 1
  • B(0,1) = A(0,0) + A(0,1) = 1 + 2 = 3
  • B(0,2) = A(0,0) + A(0,1) + A(0,2) = 1 + 2 + 3 = 6
  • B(1,0) = A(0,0) + A(1,0) = 1 + 4 = 5
  • B(1,1) = A(0,0) + A(0,1) + A(1,0) + A(1,1) = 1 + 2 + 4 + 5 = 12
  • B(1,2) = A(0,0) + A(0,1) + A(0,2) + A(1,0) + A(1,1) + A(1,2) = 1 + 2 + 3 + 4 + 5 + 6 = 21

解法

二维前缀和模板。B[i][j] = A[i][j] + B[i-1][j] + B[i][j-1] - B[i-1][j-1],遍历一次即可。时间复杂度 O(mn),空间复杂度 O(mn)。

from typing import List

def generateMatrixB(A: List[List[int]]) -> List[List[int]]:
    m, n = len(A), len(A[0])
    B = [[0] * n for _ in range(m)]
    for i in range(m):
        for j in range(n):
            B[i][j] = A[i][j]
            if i > 0:
                B[i][j] += B[i - 1][j]
            if j > 0:
                B[i][j] += B[i][j - 1]
            if i > 0 and j > 0:
                B[i][j] -= B[i - 1][j - 1]
    return B
class Solution {
    int[][] generateMatrixB(int[][] A) {
        int m = A.length, n = A[0].length;
        int[][] B = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                B[i][j] = A[i][j];
                if (i > 0) B[i][j] += B[i - 1][j];
                if (j > 0) B[i][j] += B[i][j - 1];
                if (i > 0 && j > 0) B[i][j] -= B[i - 1][j - 1];
            }
        }
        return B;
    }
}
class Solution {
public:
    vector<vector<int>> generateMatrixB(vector<vector<int>>& A) {
        int m = A.size(), n = A[0].size();
        vector<vector<int>> B(m, vector<int>(n, 0));
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                B[i][j] = A[i][j];
                if (i > 0) B[i][j] += B[i - 1][j];
                if (j > 0) B[i][j] += B[i][j - 1];
                if (i > 0 && j > 0) B[i][j] -= B[i - 1][j - 1];
            }
        }
        return B;
    }
};