LeetCode 2267. Check if There Is a Valid Parentheses String Path

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool hasValidPath(vector<vector<char>> &grid) {
int m = grid.size(), n = grid[0].size();
if (((m + n - 1) & 1) || grid[0][0] == ')' || grid[m - 1][n - 1] == '(') return false;
bool vis[m][n][(m + n + 1) / 2];
memset(vis, 0, sizeof(vis));
function<bool(int, int, int)> dfs = [&](int x, int y, int c) {
if (c > m - x + n - y + 1) return false; // pruning, too many '('.
if (x == m - 1 && y == n - 1) return c == 1;
if (vis[x][y][c]) return false;
vis[x][y][c] = true;
c += grid[x][y] == '(' ? 1 : -1;
return c >= 0 && (x < m - 1 && dfs(x + 1, y, c) || y < n - 1 && dfs(x, y + 1, c));
};
return dfs(0, 0, 0);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool hasValidPath(vector<vector<char>>& grid) {
int m = grid[0].size();
vector<__uint128_t> f(m);
f[0] = 1;
for (auto &s : grid) {
for (int i = 0; i < m; ++i) {
if (i) f[i] |= f[i - 1];
if (s[i] == '(') f[i] <<= 1;
else f[i] >>= 1;
}
}
return f.back() & 1;
}
};

References:

  1. 添加状态后 DFS + 剪枝优化(Python/Java/C++/Go)
  2. __uint128_t位运算优化动态规划