2267. Check if There Is a Valid Parentheses String Path
1. Description
You receive an m x n grid whose cells contain opening or closing parentheses.
Starting at (0, 0), reach (m - 1, n - 1) by taking only steps to the right or downward. Read each visited cell, including both endpoints, to form a string.
Determine whether at least one such path produces balanced parentheses: every prefix must contain at least as many opening parentheses as closing ones, and their total counts must match.
Return true when such a path exists, and false otherwise.
2. Example
Example 1
Input: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]
Output: true
Explanation: Paths producing “()(())” and “((()))” both satisfy the requirements.
Example 2
Input: grid = [[")",")"],["(","("]]
Output: false
Explanation: Both routes begin with a closing parenthesis, so neither can be balanced.
3. Constraints
- The grid has m rows and n columns, with 1 <= m, n <= 100.
- Each cell contains either ‘(’ or ‘)’.
4. Solutions
Dynamic Programming && Bit Manipulation
m = grid.size(), n = grid[0].size()
Time complexity: O(mn)
Space complexity: O(n)
The complexities above treat the fixed 250-bit bitset as constant size.
| |