leetcode#dp#1277. 统计全为 1 的正方形子矩阵

在这里插入图片描述


class Solution {
    public int countSquares(int[][] matrix) {
        int[][]dp = new int[matrix.length][matrix[0].length];
        int M = dp.length;
        int N = dp[0].length;
        int res = 0;
        for(int i=0;i<M;++i) {
            for(int j=0;j<N;++j) {
                 if(i==0||j==0) {
                     dp[i][j] = matrix[i][j];
                 }else if(matrix[i][j]==1) {
                     dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) + 1;
                 }
                 res += dp[i][j];

            }
        }
        return res;


    }
    int min(int... a) {
        return Arrays.stream(a).min().getAsInt();
    }
}

在这里插入图片描述


class Solution {
    public int countSquares(int[][] matrix) {
        
        int M = matrix.length;
        int N = matrix[0].length;
        int dp[] = new int[N+1];
        int res = 0;
        for(int i=1;i<=M;++i) {
            int prev = 0;
            for(int j=1;j<=N;++j) {
                if(matrix[i-1][j-1] == 1) {
                    int oldValue = dp[j];
                    dp[j] = min(prev,dp[j], dp[j-1]) + 1;
                    prev = oldValue;
                    res += dp[j];
                }else {
                    dp[j] = 0;
                }
            }
        }
        return res;


    }
    int min(int... a) {
        return Arrays.stream(a).min().getAsInt();
    }
}

由左上角往右下角遍历,前者状态不再改变,故可以直接记录在原矩阵上
以大小为二的正方形举例:
—如果存在,则左上方,上方,左方均存在大小为一的全1正方形
以大小为三的正方形举例:
—如果存在,则左上角,上方,左方均存在大小为二的全1正方形
由此动态规划得出结论

在这里插入图片描述

类似的题目还有:

https://leetcode-cn.com/problems/unique-paths/


class Solution {
    public int uniquePaths(int m, int n) {
        int[][]dp = new int[m][n];
        for(int i=0;i<m;++i ) {
            for(int j=0;j<n;++j) {
                if(i==0||j==0) dp[i][j] = 1;
                else{
                    dp[i][j] = dp[i-1][j]+dp[i][j-1];
                }
            }
        }
        return dp[m-1][n-1];
    }
    
}


class Solution {
    public int uniquePaths(int m, int n) {
       int[] pre = new int[n];
       int[] cur = new int[n];
       int[] temp = null;
       Arrays.fill(pre,1);
       Arrays.fill(cur,1);
       for(int i=1;i<m;++i) {
           for(int j=1;j<n;++j) {
               cur[j] = cur[j-1]+pre[j];
           }
           temp = pre;
           pre = cur;
           cur = temp;
           
       }
       return pre[n-1];
    }
    
}


class Solution {
    public int uniquePaths(int m, int n) {
       int[] dp = new int[n];
       Arrays.fill(dp,1);
       for(int i=1;i<m;++i) {
           for(int j=1;j<n;++j) {
               dp[j] += dp[j-1];
           }
       }
       return dp[n-1];
    }
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值