考察知识点
回溯,深度搜索
思路一
给定字符串:①首先求出不匹配的左括号数和右括号数。
②在深度搜索过程中去除不匹配的符号,举例()())()
③当左括号数等于右括号数时,判断是否匹配
代码
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
self.res=[]
left=0
right=0
#求出不匹配的左括号数和右括号数
for i in s:
if i=="(":
left+=1
if i==")":
if left>0:left-=1
else: right+=1
self.dfs(s,0,left,right)
return self.res
return list(set(self.res))
def dfs(self,s,st,l,r):
if l==0 and r==0:
if self.check(s):
self.res.append(s)
return
for i in range(st,len(s)):
if i-1>=st and s[i]==s[i-1]:continue #去除重复,例如()())()中的位置3和4
if l>0 and s[i]=="(":
self.dfs(s[0:i]+s[(i+1):],i,l-1,r)
if r>0 and s[i]==")":
self.dfs(s[0:i]+s[(i+1):],i,l,r-1)
#去掉左括号数等于右括号数,但是不匹配的组合,例如()())(
def check(self,s):
cnt=0
for i in s:
if i=="(":
cnt+=1
if i==")":
cnt-=1
if cnt<0:
return False
return cnt==0
思路二
采用两个方向处理字符串,首先从做到右,然后从右到左。
代码
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
removed = 0
results = {s}
count = {"(": 0, ")": 0}
#从左到右,去除不匹配的右括号
for i, c in enumerate(s):
if c == ")" and count["("] == count[")"]:
new_results = set()
while results:
result = results.pop()
new_results |= {result[:j] + result[j + 1:] for j in range(i - removed + 1) if result[j] == ")"}
results = new_results
removed += 1
else:
if c in count:
count[c] += 1
count = {"(": 0, ")": 0}
i = len(s)
ll = len(s) - removed
#从右到左,去除不匹配的左括号
for ii in range(ll - 1, -1, -1):
i -= 1
c = s[i]
if c == "(" and count["("] == count[")"]:
new_results = set()
while results:
result = results.pop()
new_results |= {result[:j] + result[j + 1:] for j in range(ii, ll) if result[j] == "("}
results = new_results
ll -= 1
else:
if c in count:
count[c] += 1
return list(results)