在Python中查找最小的删除所需以使括号有效
在编程中使用括号是很常见的,但是想要确保括号的有效性是一项挑战。在Python中,编写一个函数,用于删除最少数量的无效括号,使输入的字符串的所有括号都有效。
例如:
def removeInvalidParentheses(s: str) -> List[str]:
pass
print(removeInvalidParentheses("()())()"))
# 输出 ["()()()", "(())()"]
print(removeInvalidParentheses("(a)())()"))
# 输出 ["(a)()()", "(a())()"]
print(removeInvalidParentheses(")("))
# 输出 [""]
解题思路
使用深度优先搜索(DFS)和回溯算法来解决此问题。首先,我们需要统计未配对的左括号和右括号的数量,因为只有这些是不完整的。
我们将从输入字符串中的每个字符开始,并检查此字符是否是一个右括号或左括号。如果不是,则我们只需忽略它并继续处理下一个字符。如果该字符是右括号或左括号,则我们有两个选择:要么包括这个括号,要么删除它。
对于每个字符,有以下两种可能性:
- 要么我们删除该字符,然后继续搜索,因为删除右括号或左括号都会失去一次剩余删除的机会。
- 要么我们保留该字符,但是我们必须在之前没有删除该字符的情况下才能将它包括在内。
最终,我们将搜索结束并返回结果。
代码实现
下面是一个解决这个问题的Python代码实现。注意,我们将使用Python内置的集合和列表来解决这个问题。
from typing import List
def removeInvalidParentheses(s: str) -> List[str]:
# 构建通用解集
res = set()
# 获取需要删除的左右括号数
left_removed, right_removed = 0, 0
for c in s:
if c == '(':
left_removed += 1
elif c == ')':
# 无法匹配一个右括号
if left_removed == 0:
right_removed += 1
else:
left_removed -= 1
# DFS:当前位置、剩余左右括号数、剩余删除次数、当前字符串
def dfs(index: int, left_count: int, right_count: int, left_removed: int, right_removed: int, path: str):
# 如果当前位置是字符串的最后一个字符,则将结果添加到解集中(即左右括号都为0)
if index == len(s):
if left_count == right_count == 0:
res.add(path)
else:
# 获取下一个字符
cur_char = s[index]
# 去除当前字符
if cur_char == '(' and left_removed > 0:
dfs(index + 1, left_count, right_count, left_removed - 1, right_removed, path)
elif cur_char == ')' and right_removed > 0:
dfs(index + 1, left_count, right_count, left_removed, right_removed - 1, path)
# 保留当前字符
if cur_char != '(' and cur_char != ')':
dfs(index + 1, left_count, right_count, left_removed, right_removed, path + cur_char)
elif cur_char == '(':
dfs(index + 1, left_count + 1, right_count, left_removed, right_removed, path + cur_char)
elif cur_char == ')' and left_count > right_count:
dfs(index + 1, left_count, right_count + 1, left_removed, right_removed, path + cur_char)
# 进入DFS
dfs(0, 0, 0, left_removed, right_removed, "")
return list(res)
结论
在Python中,我们可以使用深度优先搜索和回溯算法来找到最小的删除次数,以使输入字符串中的所有括号都有效。以上代码已经可以实现这个功能,可以用于处理括号匹配问题。但是需要注意的是,这个算法的时间复杂度可能会很高,取决于输入字符串的长度和需要删除的括号数量。因此,在实际使用中,应该注意输入的字符串长度和需要删除的括号数量,以避免程序运行时间过长的情况。