题目链接:https://leetcode-cn.com/problems/number-of-submatrices-that-sum-to-target/
思路:计算出二维前缀和,然后暴力枚举左上角和右下角(两个坐标确定一个矩阵)即可。
二维前缀和公式:sum[i][j] = matrix[i][j] + sum[i][j - 1] + sum[i - 1][j] - sum[i - 1][j - 1] 其他的就是边界处理上的细节了,这里不做说明了(很简单~~~)。
枚举的矩阵的元素总和公式:w = sum[x][y] - sum[i - 1][y] - sum[x][j - 1] + sum[i - 1][j - 1](左上角坐标为(i,j),右下角坐标为(x,y))其他的就是边界处理上的细节了,这里不做说明了(很简单~~~)。
上代码:
class Solution {
fun numSubmatrixSumTarget(matrix: Array<IntArray>, target: Int): Int {
val sum = Array(size = matrix.size, init = { IntArray(matrix[0].size) })
for (i in matrix.indices) {
for (j in matrix[0].indices) {
when {
i == 0 && j == 0 -> sum[i][j] = matrix[i][j]
i == 0 -> sum[i][j] = matrix[i][j] + sum[i][j - 1]
j == 0 -> sum[i][j] = matrix[i][j] + sum[i - 1][j]
else -> sum[i][j] = matrix[i][j] + sum[i][j - 1] + sum[i - 1][j] - sum[i - 1][j - 1]
}
}
}
var result = 0
for (i in matrix.indices) {
for (j in matrix[0].indices) {
for (x in i until matrix.size) {
for (y in j until matrix[0].size) {
val w = when {
i == 0 && j == 0 -> sum[x][y]
i == 0 -> sum[x][y] - sum[x][j - 1]
j == 0 -> sum[x][y] - sum[i - 1][y]
else -> sum[x][y] - sum[i - 1][y] - sum[x][j - 1] + sum[i - 1][j - 1]
}
if (w == target) {
result++
}
}
}
}
}
return result
}
}