如果你对动态规划不熟悉,望转到该篇 \color{red}{如果你对动态规划不熟悉,望转到该篇~}如果你对动态规划不熟悉,望转到该篇
这是一道比较简单的题目???????????? \color{green}{这是一道比较简单的题目???? ???? ???? ~}这是一道比较简单的题目????????????
什么题可以选择动态规划来做?
1.计数
- 有多少种方式走到右下角
- 有多少种方法选出k个数是的和是sum
2.求最大值最小值
- 从左上角走到右下角路径的最大数字和
- 最长上升子序列长度
3.求存在性
- 取石子游戏,先手是否必胜
- 能不能选出k个数使得和是sum
4.综合运用
- 动态规划 + hash
- 动态规划 + 递归
- ...
leecode 221. 最大正方形
在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:4
输入:matrix = [["0","1"],["1","0"]]
输出:1
示例 3:
输入:matrix = [["0"]]
输出:0
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] 为 '0' 或 '1'
--
棒!???????????? \color{green}{棒!???? ???? ???? ~}棒!????????????
参考代码
GO语言版
func maximalSquare(matrix [][]byte) int { dp := make([][]int, len(matrix)) maxSide := 0 for i := 0; i < len(matrix); i++ { dp[i] = make([]int, len(matrix[i])) for j := 0; j < len(matrix[i]); j++ { dp[i][j] = int(matrix[i][j] - '0') if dp[i][j] == 1 { maxSide = 1 } } } for i := 1; i < len(matrix); i++ { for j := 1; j < len(matrix[i]); j++ { if dp[i][j] == 1 { dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1 if dp[i][j] > maxSide { maxSide = dp[i][j] } } } } return maxSide * maxSide } func min(x, y int) int { if x < y { return x } return y } 复制代码
NICE太简单啦???????????? \color{red}{NICE太简单啦???? ???? ???? ~}NICE太简单啦????????????
java版
class Solution { public int maximalSquare(char[][] matrix) { int maxSide = 0; if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return maxSide; } int rows = matrix.length, columns = matrix[0].length; int[][] dp = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (matrix[i][j] == '1') { if (i == 0 || j == 0) { dp[i][j] = 1; } else { dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1; } maxSide = Math.max(maxSide, dp[i][j]); } } } int maxSquare = maxSide * maxSide; return maxSquare; } } 复制代码
❤️❤️❤️❤️