这个题解采用深度优先搜索(DFS)的方法来解决删除无效括号的问题。首先,通过遍历字符串,统计需要删除的左括号和右括号的数量。然后,使用DFS递归地尝试删除字符串中的左括号或右括号,直到删除的数量满足要求。在递归过程中,如果当前字符串已经删除了所有需要删除的括号,就判断当前字符串是否有效,如果有效则加入结果集。为了避免重复结果,在递归时跳过连续相同的字符。
时间复杂度: O(2^n)
空间复杂度: O(n)
```python
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
left, right = 0, 0
for i, c in enumerate(s):
if c == '(':
left += 1
elif c == ')':
if left == 0:
right += 1
else:
left -= 1
ans = []
def dfs(s: str, open: int, l: int, r: int) -> None:
if l == 0 and r == 0:
if self.isValid(s):
ans.append(s)
for i in range(open, len(s)):
if i > open and s[i] == s[i-1]:
continue
if l + r > len(s) - i:
break
if l > 0 and s[i] == '(':
dfs(s[:i] + s[i+1:], i, l-1, r)
if r > 0 and s[i] == ')':
dfs(s[:i] + s[i+1:], i, l, r-1)
dfs(s, 0, left, right)
return ans
def isValid(self, s: str) -> bool:
cnt = 0
for c in s:
if c == '(':
cnt += 1
elif c == ')':
cnt -= 1
if cnt < 0:
return False
return cnt == 0
```