Leeetcode 221 最大正方形 DP
JAVA DP 反向:
public final int maximalSquare(char[][] matrix) { int xLen = matrix.length, yLen = matrix[0].length, re = 0; int[][] cache = new int[xLen][yLen]; for (int i = 0; i < xLen; i++) for (int j = 0; j < yLen; j++) re = Math.max(re, endOf(matrix, i, j, cache)); return re * re; } private final int endOf(char[][] matrix, int x, int y, int[][] cache) { if (matrix[x][y] == '0') return 0; if (x == 0 || y == 0) return 1; if (cache[x][y] != 0) return cache[x][y]; int re = Math.min(endOf(matrix, x - 1, y, cache), endOf(matrix, x, y - 1, cache)); re = Math.min(re, endOf(matrix, x - 1, y - 1, cache)); cache[x][y] = re + 1; return cache[x][y]; }
JS DP 正向:
/** * @param {character[][]} matrix * @return {number} */ var maximalSquare = function (matrix) { let xLen = matrix.length, yLen = matrix[0].length, re = 0, cache = new Array(xLen); for (let i = 0; i < xLen; i++) cache[i] = new Array(yLen); for (let i = 0; i < xLen; i++) { for (let j = 0; j < yLen; j++) re = Math.max(re, dp(matrix, i, j, cache)); } return re * re; }; var dp = function (matrix, x, y, cache) { let xLen = matrix.length, yLen = matrix[0].length; if (x >= xLen || y >= yLen) return 0; if (matrix[x][y] == '0') return 0; if (cache[x][y]) return cache[x][y]; let child = Math.min(dp(matrix, x + 1, y, cache), dp(matrix, x, y + 1, cache)); child = Math.min(child, dp(matrix, x + 1, y + 1, cache)); cache[x][y] = child + 1; return cache[x][y]; }
当你看清人们的真相,于是你知道了,你可以忍受孤独