二维/矩阵类DP
矩阵类的题目能用DFS解答的都要想到memoization来优化,Tree则不能用memo优化
Maximal Square
class Solution {
/*
dp[i][j] means edge length of maximal square ending with matrix[i][j] as bottom-right corner
if matrix[i][j] == 1 && matrix[i - 1][j] == 1 && matrix[i][j - 1] == 1, dp[i][j] = dp[i - 1][j - 1] + 1
state: dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
res:
res = max(res, dp[i][j] * dp[i][j])
*/
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int rows = matrix.length, cols = matrix[0].length;
int[][] dp = new int[rows][cols];
int res = 0;
//initialization
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == '1') {
dp[i][0] = 1;
res = 1;
}
}
for (int j = 0; j < cols; j++) {
if (matrix[0][j] == '1') {
dp[0][j] = 1;
res = 1;
}
}
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == '1') {
dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
res = Math.max(res, dp[i][j] * dp[i][j]);
}
}
}
return res;
}
}Count Square Submatrices with All Ones
Triangle
Minimum Path Sum
Last updated