即尋找矩陣S
中最大的被1
填充的矩形子塊面積
。矩形子塊s
的面積
即字面義:矩形子塊s
的面積。
如:S
=segmentfault
[1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0]
最大的矩形子塊面積
爲6
,此矩形子塊s
=[1 1 1; 1 1 1]
。ui
Largest Rectangle in Histogram的變形。能夠這麼轉換,二維的矩形的橫軸對應Histogram的長度,縱軸對應Histogram的高度。從左到右,從上到下遍歷一次便可。假設矩陣大小爲n * n
,時間複雜度爲O(n^2)
,空間複雜度爲O(n)
。spa
typedef unsigned int uint; static const uint MAX_SIZE = 0x100; static uint keep[MAX_SIZE], heights[MAX_SIZE]; class Solution { public: int maximalRectangle(vector<vector<char>>& matrix) { size_t rect = 0U; memset(heights, 0, sizeof(heights)); for (size_t i = matrix.size(); i--; ) { const vector<char>& vec = matrix[i]; size_t len = vec.size(), keepEnd = 0; for (keep[0] = len; len--; keep[++keepEnd] = len) { heights[len] = vec[len] == '0'? 0 : heights[len] + 1; uint tmp = heights[len], pos = keep[keepEnd]; do { uint area = heights[pos]; if (tmp >= area) break; pos = keep[--keepEnd]; if ((area *= (pos - len - 1U)) > rect) rect = area; } while (keepEnd); } while (keepEnd) { uint area = heights[keep[keepEnd]]; if ((area *= keep[--keepEnd]) > rect) rect = area; } } return rect; } };
主要應用了等價轉化的思想。code