File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -151,3 +151,34 @@ def Hungarian(seats):
151
151
if seats [i ][j ] == '.' :
152
152
count += 1
153
153
return count - Hungarian (seats )
154
+
155
+
156
+ # Time: O(m * 2^n * 2^n) = O(m * 4^n)
157
+ # Space: O(2^n)
158
+ # dp solution
159
+ class Solution3 (object ):
160
+ def maxStudents (self , seats ):
161
+ """
162
+ :type seats: List[List[str]]
163
+ :rtype: int
164
+ """
165
+ def popcount (n ):
166
+ result = 0
167
+ while n :
168
+ n &= n - 1
169
+ result += 1
170
+ return result
171
+
172
+ dp = {0 : 0 }
173
+ for row in seats :
174
+ invalid_mask = sum (1 << c for c , v in enumerate (row ) if v == '#' )
175
+ new_dp = {}
176
+ for mask1 , v1 in dp .iteritems ():
177
+ for mask2 in xrange (1 << len (seats [0 ])):
178
+ if (mask2 & invalid_mask ) or \
179
+ (mask2 & (mask1 << 1 )) or (mask2 & (mask1 >> 1 )) or \
180
+ (mask2 & (mask2 << 1 )) or (mask2 & (mask2 >> 1 )):
181
+ continue
182
+ new_dp [mask2 ] = max (new_dp .get (mask2 , 0 ), v1 + popcount (mask2 ))
183
+ dp = new_dp
184
+ return max (dp .itervalues ()) if dp else 0
You can’t perform that action at this time.
0 commit comments