输入:"()())()"输出:["(())()","()()()"]
输入:"(a)())()"输出: ["(a)()()", "(a())()"]
from typing import List
class Solution:
"""
@param s: The input string
@return: Return all possible results
"""
def remove_invalid_parentheses(self, s: str) -> List[str]:
res = []
def helper(s, start, l_remove, r_remove):
if l_remove == 0 and r_remove==0:
if is_valid(s):
res.append(s)
# return
# if l_remove + r_remove > len(s): #剩下的s太短,不够移除
# return
for i in range(start, len(s)): #试探每个字符是否可以移除
if i != start and s[i] == s[i-1]: #重复的字符移第一个就行,这里是去重,结果就无需set
continue
c = s[i]
if c == '(' and l_remove > 0:
helper(s[:i]+s[i+1:], i, l_remove - 1, r_remove)
if c == ')' and r_remove > 0:
helper(s[:i]+s[i+1:], i, l_remove, r_remove - 1)
def is_valid(string):
l, r = count_left_right_remove(string)
return l == 0 and r == 0
def count_left_right_remove(s):
l_remove, r_remove = 0, 0
for char in s:
if char == '(':
l_remove += 1
elif char == ')':
if l_remove > 0:
l_remove -= 1
else:
r_remove += 1
return l_remove, r_remove
l_remove, r_remove = count_left_right_remove(s)
helper(s, 0, l_remove, r_remove)
return res