本文主要是介绍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 = 0for 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 += 1else:breakreturn ans
提交代码评测得到:耗时1591ms,占用内存65.8MB。
这篇关于Leetcode 3070. Count Submatrices with Top-Left Element and Sum Less Than k的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!