301 Remove Invalid Parentheses
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Examples:
"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]
Solution
屁都不会,心烦!
def helper(s, istart, i_delete, res, left, right):
i, n = istart, len(s)
count = 0
for i in range(istart, n, 1):
if ( s[i] == left ): count += 1
if ( s[i] == right ): count -= 1
if ( count != -1 ): continue
for j in range(i_delete, i+1, 1):
if ( s[j] == right and ( j == i_delete or s[j-1] != right) ):
helper(s[0:j] + s[j+1:], i, j, res, left, right)
return res
if ( count == 0 ):
if ( left == '(' ): res.append(s)
else:
s = s[::-1]
res.append(s)
return
s = s[::-1]
helper(s, 0, 0, res, ')', '(')
return
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
res = []
helper(s, 0, 0, res, '(', ')')
return res