当前位置: 首页 > news >正文

LeetCode1504. Count Submatrices With All Ones

文章目录

    • 一、题目
    • 二、题解

一、题目

Given an m x n binary matrix mat, return the number of submatrices that have all ones.

Example 1:

Input: mat = [[1,0,1],[1,1,0],[1,1,0]]
Output: 13
Explanation:
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rectangle of side 2x2.
There is 1 rectangle of side 3x1.
Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.
Example 2:

Input: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]
Output: 24
Explanation:
There are 8 rectangles of side 1x1.
There are 5 rectangles of side 1x2.
There are 2 rectangles of side 1x3.
There are 4 rectangles of side 2x1.
There are 2 rectangles of side 2x2.
There are 2 rectangles of side 3x1.
There is 1 rectangle of side 3x2.
Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.

Constraints:

1 <= m, n <= 150
mat[i][j] is either 0 or 1.

二、题解

class Solution {
public:int numSubmat(vector<vector<int>>& mat) {int res = 0;int m = mat.size(),n = mat[0].size();vector<int> heights(n,0);for(int i = 0;i < m;i++){for(int j = 0;j < n;j++){heights[j] = mat[i][j] == 0 ? 0 : heights[j] + 1;}res += countFromBottom(heights);}return res;}int countFromBottom(vector<int>& heights){int n = heights.size();int res = 0;stack<int> st;for(int i = 0;i < n;i++){while(!st.empty() && heights[i] <= heights[st.top()]){int cur = st.top();st.pop();if(heights[cur] > heights[i]){int left = st.empty() ? -1 : st.top();int len = i - left - 1;int bottom = max(left == -1 ? 0 : heights[left],heights[i]);res += (heights[cur] - bottom) * len * (len + 1) / 2;}}st.push(i);}while(!st.empty()){int cur = st.top();st.pop();int left = st.empty() ? -1 : st.top();int len = n - left - 1;int bottom = left == -1 ? 0 : heights[left];res += (heights[cur] - bottom) * len * (len + 1) / 2;}return res;}
};
http://www.lryc.cn/news/289805.html

相关文章:

  • (每日持续更新)信息系统项目管理(第四版)(高级项目管理)考试重点整理第8章 项目整合管理(九)
  • 帕金森早期诊断准确率提高至 90.2%,深圳先进院联合中山一院提出 GSP-GCNs 模型
  • java servlet果蔬产业监管系统Myeclipse开发mysql数据库web结构java编程计算机网页项目
  • Flask 入门
  • 微信小程序Skyline在手机端不渲染的问题之一及其解决方式
  • 怎样做好Code Review
  • 臻于至善,CodeArts Snap 二维绘图来一套不?
  • STM32学习笔记(二) —— 调试串口
  • Ubuntu20.0.4下设置frpc开机自启动
  • 05 Redis之Benchmark+简单动态字符串SDS+集合的底层实现
  • 【C++】priority_queue优先队列
  • 蓝桥杯---三国游戏
  • 设计一个分布式ID
  • 259:vue+openlayers: 显示海量多边形数据,10ms加载完成
  • Go Zero微服务个人探究之路(十)实战走通微服务前台请求调用的一套流程model->rpc微服务->apiHTTP调用
  • K8s 安装部署-Master和Minion(Node)
  • 从零学习Linux操作系统 第二十部分 mariadb数据库的管理
  • 数据脱敏和数据加密有什么区别
  • 主流排序算法
  • MySql的使用方法
  • C#,数据检索算法之三元搜索(Ternary Search)的源代码
  • windbg:常用指令
  • 23. 集合类
  • OpenAI平台:引领人工智能的创新与应用
  • redis原理(五)Lua语言
  • SOHO外贸怎么建网站?做海洋建站的步骤?
  • [论文阅读] |RAG评估_Retrieval-Augmented Generation Benchmark
  • 【Linux】动态库和静态库——动态库和静态库的打包和使用、gcc编译、拷贝到系统默认的路径、建立软连接
  • 【Redis】Redis有哪些适合的场景
  • uniapp上传音频文件到服务器