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

Problem

You are given a 0-indexed integer matrix grid and an integer k.

Return the number of submatrices that contain the top-left element of the grid, and have a sum less than or equal to k.

Algorithm

Dynamic programming (DP): let f[i][j] be the sum of the submatrix from (0,0) to (i,j), and count all positions where f[i][j] ≤ k.

Code

python3 复制代码
class Solution:
    def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
        m, n, ans = len(grid), len(grid[0]), 0
        for i in range(m):
            for j in range(n):
                if i > 0:
                    grid[i][j] += grid[i-1][j]
                if j > 0:
                    grid[i][j] += grid[i][j-1]
                if i > 0 and j > 0:
                    grid[i][j] -= grid[i-1][j-1]
                if grid[i][j] <= k:
                    ans += 1
        
        return ans
相关推荐
笨笨饿2 小时前
32_复变函数在工程中实际应用区别于联系
linux·服务器·c语言·人工智能·单片机·算法·学习方法
会编程的土豆2 小时前
【数据结构与算法】拓扑排序2
数据结构·算法·leetcode
Boop_wu2 小时前
[Java 算法] 栈
java·开发语言·算法
追风落叶乔木生2 小时前
字节跳动后端一面全解析|基础+算法真题(2026最新版)
算法·哈希算法
来自远方的老作者2 小时前
第7章 运算符-7.5 比较运算符
开发语言·数据结构·python·算法·代码规范·比较运算符
We་ct2 小时前
LeetCode 201. 数字范围按位与:位运算高效解题指南
开发语言·前端·javascript·算法·leetcode·typescript
wanderist.2 小时前
图论模板整理
算法·深度优先·图论
超级大只老咪2 小时前
线性递推通用模板
java·开发语言·算法
17(无规则自律)3 小时前
DFS:带重复项的全排列,程序运行全流程解析
c++·算法·深度优先