[leetcode] 221. Maximal Square 解题报告
来源:互联网 发布:手机号小号软件 编辑:程序博客网 时间:2024/06/05 19:49
题目链接:https://leetcode.com/problems/maximal-square/
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
For example, given the following matrix:
1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0Return 4.
思路:一道比较明显的动态规划题目。因为是要寻找一个正方形,所以就比较简单一些,借助一个辅助数组dp[][],dp[i][j]表示当前正方形的边长,并且其值由两种情况构成:
1. 如果matrix[i-1][j-1] = 1, 因为是正方形,则其值为min(dp[i-1][j-1],dp[i][j-1],dp[i-1][j])中的最小值加1,小正方形构成大正方形,状态转移方程即为:
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;
2. 如果matrix[i-1][j-1] = 0,则dp[i][j] = 0;
时间复杂度为O(m*n),空间复杂度为O(m*n)
代码如下:
class Solution {public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.size()==0) return 0; int row = matrix.size(), col = matrix[0].size(), ans = 0; vector<vector<int>> dp(row+1, vector<int>(col+1, 0)); for(int i = 1; i <= row; i++) { for(int j = 1; j <= col; j++) { if(matrix[i-1][j-1]=='0') continue; dp[i][j] = min(dp[i-1][j], min(dp[i][j-1], dp[i-1][j-1])) + 1; ans = max(ans, dp[i][j]); } } return ans*ans; }};
0 0
- [leetcode] 221. Maximal Square 解题报告
- [Leetcode] 221. Maximal Square 解题报告
- LeetCode-Maximal Square-解题报告
- [leetcode] 221.Maximal Square
- 【leetcode】221. Maximal Square
- [LeetCode]221. Maximal Square
- leetcode 221. Maximal Square
- 221. Maximal Square LeetCode
- LeetCode 221. Maximal Square
- LeetCode *** 221. Maximal Square
- LeetCode-221.Maximal Square
- leetcode.221. Maximal Square
- Leetcode 221. Maximal Square
- [leetcode]221. Maximal Square
- [LeetCode]--221. Maximal Square
- leetcode 221. Maximal Square
- Leetcode 221. Maximal Square
- Leetcode 221. Maximal Square
- Windows程序设计--击键消息和字符消息
- typeof instanceof 的应用场景
- vs2008下MFC中采用ado连接MySQL(ODBC、非ODBC或C API方式)
- SubLime Text3 打造Python的IDE
- 寻找峰值 查看运行结果 ——LintCode
- [leetcode] 221. Maximal Square 解题报告
- cocos2d 中文显示问题解决
- codeforce B. Preparing Olympiad (DFS+回溯)/(暴力状压)
- 使用异步Servlet改进应用性能
- 实现输出h264直播流的rtmp服务器
- Android与服务器端通信时 部分中文出现乱码
- DOS命令(二)
- Git简介
- ramdisk.img和system.img解压