classSolution { public: intlargest1BorderedSquare(vector<vector<int>>& grid){ auto up = grid, down = grid, left = grid, right = grid; constint R = grid.size(), C = grid[0].size(); for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { if (i == 0) { up[i][j] = grid[i][j] == 1 ? 1 : 0; } else { up[i][j] = grid[i][j] == 1 ? up[i-1][j] + 1 : 0; } if (j == 0) { left[i][j] = grid[i][j] == 1 ? 1 : 0; } else { left[i][j] = grid[i][j] == 1 ? left[i][j-1] + 1 : 0; } } } for (int i = R - 1; i >= 0; --i) { for (int j = C - 1; j >= 0; --j) { if (i == R - 1) { down[i][j] = grid[i][j] == 1 ? 1 : 0; } else { down[i][j] = grid[i][j] == 1 ? down[i+1][j] + 1 : 0; } if (j == C - 1) { right[i][j] = grid[i][j] == 1 ? 1 : 0; } else { right[i][j] = grid[i][j] == 1 ? right[i][j+1] + 1 : 0; } } } int ans = 0; for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { for (int k = min(up[i][j], left[i][j]); k > ans; --k) { int corner_i = i - k + 1; int corner_j = j - k + 1; if (down[corner_i][corner_j] >= k && right[corner_i][corner_j] >= k) { ans = k; break; } } } } return ans * ans; } };
1140. Stone Game II
常规思路就是一个DP。这里采用了top-down的memorization的写法,实现起来更好实现。
状态转移方程。
dp[begin][M] = max(sum of prefix + sum of suffix - dp[begin + X][max(X, M)]), for X in [1, 2 * M].