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];
}
}