LeetCode Maximal Square

来源:互联网 发布:pscc是什么软件 编辑:程序博客网 时间:2024/06/05 15:31

原题链接在这里:https://leetcode.com/problems/maximal-square/

这是一道DP题,存储历史信息是到当前点能有的最大square, 用二维数组dp存储。

更新方式是若当前点为0,则不更新,若当前点为1,则取上dp[i-1][j], 左dp[i][j-1], 左上dp[i-1][j-1]的中的最小值,开根号加一,最后平方为dp[i][j].

初始第一行和第一列,为'1'的时候填成1.

Note: 1. 给的matrix数组是char, 所以比较时是根char型'0', '1' 比较,不是int

2. 更新dp时,首先注意当matrix[i][j]为'1'时才更新,if 条件别忘了。然后Math.pow, Math.sqrt返回的都是double型,别忘了cast

3. res 的初始化,因为更新dp[i][j]的双重for loop是从i=1,j=1开始的,所以res时从第二行第二列开始更新,若matrix只有一行时就会出问题。所以res在刚开始对dp第一行第一列赋值时就要跟着更新。

AC Java:

public class Solution {    public int maximalSquare(char[][] matrix) {        //DP, maintain the maximal square for each node        //当matrix当前点为1时,取上,左,左上最小值开根号,得到边长,再加一,更新边长,最后平方更新当前面积        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){            return 0;        }        int h = matrix.length;        int w = matrix[0].length;        int res = 0;        int[][] dp = new int[h][w];        for(int i = 0; i < h; i++){            dp[i][0] = matrix[i][0] == '0' ? 0:1;            res = Math.max(res,dp[i][0]);       //error        }        for(int j = 0; j < w; j++){            dp[0][j] = matrix[0][j] == '0' ? 0:1;            res = Math.max(res,dp[0][j]);        }        for(int i = 1; i < h; i++){            for(int j = 1; j<w; j++){                if(matrix[i][j] == '1'){ //error                    dp[i][j] = (int)Math.pow(Math.sqrt(Math.min(Math.min(dp[i-1][j-1], dp[i-1][j]), dp[i][j-1])) + 1, 2);                     res = Math.max(res, dp[i][j]);                }                            }        }        return res;    }}


0 0
原创粉丝点击