Leetcode 3070. Count Submatrices with Top-Left Element and Sum Less Than k

  • Leetcode 3070. Count Submatrices with Top-Left Element and Sum Less Than k
    • 1. 解题思路
    • 2. 代码实现
  • 题目链接:3070. Count Submatrices with Top-Left Element and Sum Less Than k

1. 解题思路

这一题就是一个二维的累积数组的问题,我们直接求一下累积数组然后找一下满足条件的矩阵就行了。

另外,由于只需要寻找和不大于k的矩阵,因此我们可以在和超过k时提前跳出来进行剪枝,从而优化执行效率。

2. 代码实现

给出python代码实现如下:

class Solution:
    def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
        n, m = len(grid), len(grid[0])
        s = [[0 for _ in range(m+1)] for _ in range(n+1)]
        ans = 0
        for i in range(n):
            for j in range(m):
                s[i+1][j+1] = grid[i][j] + s[i+1][j] + s[i][j+1] - s[i][j]
                if s[i+1][j+1] <= k:
                    ans += 1
                else:
                    break
        return ans

提交代码评测得到:耗时1591ms,占用内存65.8MB。

你可能感兴趣的:(leetcode笔记,leetcode,3070,leetcode周赛387,leetcode,medium,二维累积数组,leetcode题解)