(Version 0.1)
Before doing this problem, I just made scramble String (http://www.cnblogs.com/icecreamdeqinw/p/4338731.html), so maximal Rectangle This problem after my idea naturally follow the inertia feel certainly can use a three-dimensional DP solution, as to the time and space complexity can pass leetcode OJ is not good to say.
(i) three-dimensional DP with no brain
In order to familiarize yourself with the three-dimensional DP thought model just learned, first wrote a three-dimensional array isline[i][j][k] to save the beginning of line I to the end of the first j is the K element can constitute a full of ' 1 ' composed of a horizontal line, the outer layer according to the length of lines from short to long cycle, The middle loop starts at the beginning of the line, and then the inner layer moves the line in order from top to bottom, the complexity of the code is high, but the Leetcode OJ is not expected, and the code is as follows:
1 Public classSolution {2 Public intMaximalrectangle (Char[] matrix) {3 if(Matrix.length = = 0) {4 return0;5 }6 Boolean[][][] Isline =New Boolean[Matrix.length] [Matrix[0].length] [Matrix[0].length];7 for(inti = 0; i < matrix.length; i++) {8 for(intj = 0; J < Matrix[0].length; J + +) {9 if(Matrix[i][j] = = ' 1 ') {TenISLINE[I][J][J] =true; One } A } - } - intresult = 0; the for(inti = 0; i < matrix.length; i++) { - for(intL = 2; L <= matrix[0].length; l++) { - for(intj = 0; J <= Matrix[0].length-l; J + +) { - intEnd = j + L-1; + if(Matrix[i][end] = = ' 1 ' && isline[i][j][end-1]) { -Isline[i][j][end] =true; + } A } at } - } - for(intL = 1; L <= matrix[0].length; l++) {//length of the line - for(inti = 0; I <= matrix[0].length-l; i++) {//start Point of the line - intbound = i + l-1; - intArea = 0; in for(intj = 0; J < Matrix.length; J + +) {//Row # - if(Isline[j][i][bound]) { toArea + =l; +result =Math.max (result, area); -}Else { theArea = 0; * } $ }Panax Notoginseng } - } the returnresult; + } A}
Although this code through the Leetcode OJ, but in fact, because the time limit of the problem is very loose, most of the Java code through the code is less than half the time spent, that the solution must not be a good solution, need to be optimized from different ideas.
(ii) Optimization
After using the no-brain three-dimensional DP, as mentioned above, to see that Leetcode has a stack in the category tag for this problem, it is possible to use a method similar to largest Rectangle in histogram using stack storage boundaries, When you swipe from top to bottom with different lengths, you can cycle from small to large in length. Another review of the code in the cycle order will find that this is actually a cache friendly code, because the most inner layer of each cycle changes are the first subscript, so if we change the direction of the sweep from vertical to horizontal, and the three-dimensional DP array into the vertical line, perhaps there will be a performance improvement.
adjourned
[Leetcode] Maximal Rectangle