[Dynamic Programming] leetcode 85 Maximal Rectangle

problem:https://leetcode.com/problems/maximal-rectangle/

         My approach is to put it into one-dimensional. First calculate the prefix and each column.

         After scanning rows, each row may be regarded as the abscissa, the current value as an height, to obtain a histogram of the same thing, just next calculation of the maximum rectangular area histogram. The time complexity of O (N3)

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if (matrix.size() == 0) return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        int max = 0;
        vector<vector<int>> dp(m, vector<int>(n, 0));
        for (int i = 0;i<m;i++) {
            for (int j = 0;j<n;j++) {
                if (matrix[i][j] == '1') {
                    if (i >= 1) dp[i][j] = dp[i - 1][j] + 1;
                    else dp[i][j] = 1;
                   
                }
            }
        }
        for (int i = 0;i < m;i++) {
            for (int j = 0;j < n;j++) {
                if (dp[i][j] > 0) {
                    int height = dp[i][j];
                    for (int k = j;k >= 0;k--) {
                        if (dp[i][k] == 0) break;
                        if (dp[i][k] < height) height = dp[i][k];
                        int r = (j - k + 1) * height;
                        if (r > max) max = r;
                    }
                }
            }
        }
        return max;
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11299856.html