솔루션: 합계가 목표로 되는 부분 행렬의 수

이것은 일련의 Leetcode 솔루션 설명( )의 일부입니다. 이 솔루션이 마음에 들었거나 유용하다고 생각되면 이 게시물에 좋아요를 누르거나 찬성 투표my solution post on Leetcode's forums를 해주세요.


Leetcode 문제 #1074(어려움): 합계가 목표로 되는 부분 행렬의 수




설명:



(다음으로 이동: Solution Idea || 코드: JavaScript | Python | Java | C++ )

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.
Visual:
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.
Example 3:
Input: matrix = [[904]], target = 0
Output: 0



제약:



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



아이디어:



(다음으로 이동: Problem Description || 코드: JavaScript | Python | Java | C++ )

이 문제는 본질적으로 #560. Subarray Sum Equals K (S.S.E.K) 의 2차원 버전입니다. 각 행 또는 각 열에서 접두사 합계를 사용하여 이 문제를 O(M) SSEK의 N^2 반복 또는 O(N) SSEK의 M^2 반복으로 압축할 수 있습니다.

SSEK 솔루션에서는 실행 합계(csum)를 유지하면서 배열을 반복하면서 찾은 다른 값을 저장하기 위해 결과 맵(res)을 활용하여 대상 합계가 있는 하위 배열의 수를 찾을 수 있습니다. 접두사 합계 배열의 경우와 마찬가지로 i와 j 사이의 하위 배열의 합은 0에서 j까지의 하위 배열의 합에서 0에서 i-1까지의 하위 배열의 합을 뺀 것과 같습니다.

i, j 값의 모든 쌍에 대해 sum[0,j] - sum[0,i-1] = T인지 반복적으로 확인하는 대신 sum[0,j] - T = sum[0, i-1] 그리고 이전의 모든 합계 값이 res에 저장되었으므로 sum[0,j] - T에 대한 조회를 수행하여 일치하는 항목이 있는지 확인할 수 있습니다.

이 솔루션을 2차원 행렬(M)에 외삽할 때 먼저 행 또는 열의 접두사 합계를 구해야 합니다(원래 값이 다시 필요하지 않으므로 추가 공간을 피하기 위해 내부에서 수행할 수 있음). 그런 다음 행/열의 반대 순서로 M을 다시 반복해야 합니다. 여기서 접두사 합계를 사용하면 열 또는 행 그룹을 1차원 배열인 것처럼 처리하고 SSEK 알고리즘을 적용할 수 있습니다.


구현:



네 가지 언어 모두의 코드에는 약간의 차이만 있습니다.


자바스크립트 코드:



(다음으로 이동: Problem Description || Solution Idea )

var numSubmatrixSumTarget = function(M, T) {
    let xlen = M[0].length, ylen = M.length,
        ans = 0, res = new Map()
    for (let i = 0, r = M[0]; i < ylen; r = M[++i]) 
        for (let j = 1; j < xlen; j++)
            r[j] += r[j-1]
    for (let j = 0; j < xlen; j++)
        for (let k = j; k < xlen; k++) {
            res.clear(), res.set(0,1), csum = 0
            for (let i = 0; i < ylen; i++) {
                csum += M[i][k] - (j ? M[i][j-1] : 0)
                ans += (res.get(csum - T) || 0)
                res.set(csum, (res.get(csum) || 0) + 1)
            }
        }
    return ans
};



파이썬 코드:



(다음으로 이동: Problem Description || Solution Idea )

class Solution:
    def numSubmatrixSumTarget(self, M: List[List[int]], T: int) -> int:
        xlen, ylen, ans, res = len(M[0]), len(M), 0, defaultdict(int)
        for r in M:
            for j in range(1, xlen):
                r[j] += r[j-1]
        for j in range(xlen):
            for k in range(j, xlen):
                res.clear()
                res[0], csum = 1, 0
                for i in range(ylen):
                    csum += M[i][k] - (M[i][j-1] if j else 0)
                    ans += res[csum - T]
                    res[csum] += 1
        return ans



자바 코드:



(다음으로 이동: Problem Description || Solution Idea )

class Solution {
    public int numSubmatrixSumTarget(int[][] M, int T) {
        int xlen = M[0].length, ylen = M.length, ans = 0;
        Map<Integer, Integer> res = new HashMap<>();
        for (int[] r : M)
            for (int j = 1; j < xlen; j++)
                r[j] += r[j-1];
        for (int j = 0; j < xlen; j++)
            for (int k = j; k < xlen; k++) {
                res.clear();
                res.put(0,1);
                int csum = 0;
                for (int i = 0; i < ylen; i++) {
                    csum += M[i][k] - (j > 0 ? M[i][j-1] : 0);
                    ans += res.getOrDefault(csum - T, 0);
                    res.put(csum, res.getOrDefault(csum, 0) + 1);
                }
            }
        return ans;
    }
}



C++ 코드:



(다음으로 이동: Problem Description || Solution Idea )

class Solution {
public:
    int numSubmatrixSumTarget(vector<vector<int>>& M, int T) {
        int xlen = M[0].size(), ylen = M.size(), ans = 0;
        unordered_map<int, int> res;
        for (int i = 0; i < ylen; i++)
            for (int j = 1; j < xlen; j++)
                M[i][j] += M[i][j-1];
        for (int j = 0; j < xlen; j++)
            for (int k = j; k < xlen; k++) {
                res.clear();
                res[0] = 1;
                int csum = 0;
                for (int i = 0; i < ylen; i++) {
                    csum += M[i][k] - (j ? M[i][j-1] : 0);
                    ans += res.find(csum - T) != res.end() ? res[csum - T] : 0;
                    res[csum]++;
                }
            }
        return ans;
    }
};

좋은 웹페이지 즐겨찾기