1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| class Solution { public: int ways(vector<string>& pizza, int k) { const int MOD = 1e9 + 7; int m = pizza.size() , n = pizza[0].size(); int s[m + 1][n + 1]; memset(s,0,sizeof s); for(int i = 0 ; i < m ; i++){ for(int j = 0 ; j < n ; j++){ s[i + 1][j + 1] = s[i + 1][j] + s[i][j + 1] - s[i][j] + (pizza[i][j] & 1) ; } }
function<int(int,int,int,int)> get = [&](int x1,int y1,int x2,int y2) -> int{ return s[x2][y2] - s[x2][y1] - s[x1][y2] + s[x1][y1]; };
int memo[k][m][n]; memset(memo,-1,sizeof memo);
function<int(int,int,int)> dfs = [&](int c,int i, int j) -> int{ if(c == 0){ return get(i,j,m,n) ? 1 : 0; }
int &res = memo[c][i][j]; if(res != -1){ return res; }
res = 0;
for(int j2 = j;j2 < n ; j2++){ if(get(i,j,m,j2)){ res = (res + dfs(c- 1,i,j2)) % MOD; } }
for(int i2 = i ; i2 < m ; i2++){ if(get(i,j,i2,n)){ res = (res + dfs(c-1,i2,j)) % MOD; } }
return res; };
return dfs(k - 1,0,0); } };
|