File tree Expand file tree Collapse file tree 3 files changed +41
-0
lines changed Expand file tree Collapse file tree 3 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 90
90
206. 反转链表
91
91
215. 数组中的第K个最大元素
92
92
216. 组合总和 III
93
+ 221. 最大正方形
93
94
226. 翻转二叉树
94
95
232. 用栈实现队列
95
96
234. 回文链表
Original file line number Diff line number Diff line change 78
78
152. 乘积最大子数组
79
79
188. 买卖股票的最佳时机 IV
80
80
198. 打家劫舍
81
+ 221. 最大正方形
81
82
279. 完全平方数
82
83
300. 最长上升子序列
83
84
309. 最佳买卖股票时机含冷冻期
Original file line number Diff line number Diff line change
1
+ // 221. 最大正方形
2
+
3
+
4
+ /*
5
+ 动态规划:
6
+ 1、定义dp数组:dp[row][col] 表示以 matrix[row-1][col-1] 为右下角的正方形的最大边长
7
+ 2、初始化:由于状态转移方程要用到上一行和上一列,所以二维dp数组扩容首行首列,初始化为0
8
+ 3、状态转移方程:
9
+ 若某格子值为 1,则以此为右下角的正方形的最大边长为 左面的正方形、上面的正方形、左上的正方形 的最小边长加1
10
+ 左、上、左上取最小边长,是因为木桶原理,只能取最小才能构成正方形,其他两个边长肯定大于等于最小边长,三个正方形加上当前格子,就能构成新的边长为 最小边长加1 的正方形
11
+ 4、遍历dp数组填表:两个for循环遍历二维dp数组,当格子为1时,根据状态转移方程填表
12
+ 5、返回结果:边计算边保留最大边长,最后返回面积
13
+
14
+ 以最后一个为例:
15
+ matrix dp
16
+ 1 1 1 1 1 1 1 1
17
+ 1 1 1 1 1 2 2 2
18
+ 1 1 1 1 ==> 1 2 3 3 ==> dp[3][3] = min(2, 3, 3) + 1
19
+ 0 1 1 1 0 1 2 3
20
+ */
21
+ class Solution {
22
+ public int maximalSquare (char [][] matrix ) {
23
+ int m = matrix .length , n = matrix [0 ].length ;
24
+ if (m < 1 || n < 1 ) {
25
+ return 0 ;
26
+ }
27
+ int maxSide = 0 ;
28
+ int [][] dp = new int [m + 1 ][n + 1 ];
29
+ for (int row = 1 ; row <= m ; row ++) {
30
+ for (int col = 1 ; col <= n ; col ++) {
31
+ if (matrix [row - 1 ][col - 1 ] == '1' ) {
32
+ dp [row ][col ] = Math .min (dp [row - 1 ][col - 1 ], Math .min (dp [row - 1 ][col ], dp [row ][col - 1 ])) + 1 ;
33
+ maxSide = Math .max (maxSide , dp [row ][col ]);
34
+ }
35
+ }
36
+ }
37
+ return maxSide * maxSide ;
38
+ }
39
+ }
You can’t perform that action at this time.
0 commit comments