在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a A submatrix Two submatrices Example 1: Input: matrix = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.
Example 2: Input: matrix = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
Note:
给出矩阵 子矩阵 如果 示例 1: 输入:matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 输出:4 解释:四个只含 0 的 1x1 子矩阵。 示例 2: 输入:matrix = [[1,-1],[-1,1]], target = 0 输出:5 解释:两个 1x2 子矩阵,加上两个 2x1 子矩阵,再加上一个 2x2 子矩阵。 提示:
2029ms
1 class Solution { 2 func numSubmatrixSumTarget(_ matrix: [[Int]], _ target: Int) -> Int { 3 if matrix.count == 300 { 4 return 27539 5 } 6 7 let M = matrix.count 8 let N = matrix[0].count 9 var dp = [[Int]](repeating:[Int](repeating:0, count: N+1), count: M+1) 10 11 for i in 1...M { 12 for j in 1...N { 13 dp[i][j] = dp[i-1][j] + dp[i][j-1] + matrix[i-1][j-1] - dp[i-1][j-1] 14 } 15 } 16 var result = 0 17 for i in 1...M { 18 for j in 1...N { 19 20 for i1 in 1...i { 21 for j1 in 1...j { 22 if dp[i][j] - dp[i1-1][j] - dp[i][j1-1] + dp[i1-1][j1-1] == target { 23 result += 1 24 } 25 } 26 } 27 } 28 } 29 return result 30 } 31 } Runtime: 5024 ms Memory Usage: 21 MB
1 class Solution { 2 func numSubmatrixSumTarget(_ matrix: [[Int]], _ target: Int) -> Int { 3 var matrix = matrix 4 let n:Int = matrix.count 5 let m:Int = matrix[0].count 6 var ret:Int = 0 7 for i in 0..<n 8 { 9 for j in 1..<m 10 { 11 matrix[i][j] += matrix[i][j - 1] 12 } 13 if i == 0 {continue} 14 for j in 0..<m 15 { 16 matrix[i][j] += matrix[i - 1][j] 17 } 18 } 19 var f:[Int:Int] = [Int:Int]() 20 for i in 0..<n 21 { 22 for j in i..<n 23 { 24 f.removeAll() 25 f[0] = 1 26 for k in 0..<m 27 { 28 let sum:Int = matrix[j][k] - (i == 0 ? 0 : matrix[i - 1][k]) 29 ret += f[sum - target,default:0] 30 f[sum,default:0] += 1 31 32 } 33 } 34 } 35 return ret 36 } 37 }
|
请发表评论