-
class Solution(object):
-
def removeInvalidParentheses(self, s):
-
"""
-
:type s: str
-
:rtype: List[str]
-
"""
-
if len(s) == 0:
-
return [""]
-
count1 = 0
-
count2 = 0
-
for str_num in s:
-
count1 += (str_num=="(")
-
if count1 == 0:
-
count2 += (str_num==")")
-
else:
-
count1 -= (str_num==")")
-
start = 0
-
res = []
-
self.DFS(s, start, count1, count2, res)
-
return res
-
def DFS(self, s, start, count1, count2, res):
-
if count1 == 0 and count2 == 0: #一样多
-
if self.isValid(s):
-
res.append(s)
-
return
-
else:
-
for i in range(start, len(s)):
-
if i != start and s[i] == s[i-1]:
-
continue #重复的只计算一次
-
elif count1 > 0 and s[i] == "(": #左多
-
self.DFS(s[:i]+s[i+1:], i, count1-1, count2, res)
-
elif count2 > 0 and s[i] == ")": #右多
-
self.DFS(s[:i]+s[i+1:], i, count1, count2-1, res)
-
def isValid(self, string):
-
count = 0
-
for i in range(len(string)):
-
if string[i] == "(":
-
count += 1
-
elif string[i] == ")":
-
count -= 1
-
if count < 0:
-
return False
-
return count == 0
给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。 返回所有可能的结果。答案可以按 任意顺序 返回
最新推荐文章于 2022-10-29 07:58:49 发布