leetcode 301. 删除无效的括号

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 ).

Example 1:

Input: "()())()"
Output: ["()()()", "(())()"]

Example 2:

Input: "(a)())()"
Output: ["(a)()()", "(a())()"]

Example 3:

Input: ")("
Output: [""]
  • bfs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from collections import deque
class Solution(object):
def removeInvalidParentheses(self, s):
self.solution_found = False
self.visited_potential_solutions = set()
self.results = set()
self.bfs(s,0)
return list(self.results)

def bfs(self, s, characters_removed):
if s is "" or s is None:
return
queue = deque()
queue.append(s)
while queue:
current = queue.popleft()
if self.is_valid(current):
self.solution_found = True
self.results.add(current)
continue
if self.solution_found:
continue
for i,c in enumerate(current):
if not self.is_parenthesis(c):
continue
potential_solution = current[:i]+current[i+1:]
if potential_solution not in self.visited_potential_solutions:
self.visited_potential_solutions.add(potential_solution)
queue.append(potential_solution)

def is_valid(self, s):
summatory = 0
for c in s:
if c == '(':
summatory += 1
if c == ')':
summatory -= 1
if summatory < 0:
return False
return summatory == 0

def is_parenthesis(self, c):
return c in ['(', ')']
  • dfs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):
def removeInvalidParentheses(self, s):
self.ans = []
self.dfs(s, 0, 0, ['(',')'])
if len(self.ans) == 0:
return [""]
return self.ans

def dfs(self, s, last_i, last_j, par):
count = 0
for i in range(last_i, len(s)):
if s[i] == par[0]: count +=1
if s[i] == par[1]: count -=1
if count >=0:
continue
for j in range ( last_j, i+1):
if s[j] == par[1] and (j == last_j or s[j-1] != par[1]):
self.dfs(s[:j] + s[j+1:], i, j, par )
return

s_reversed = s[::-1]
if par[0] == '(':
self.dfs(s_reversed, 0, 0, [')','('])
else:
self.ans.append(s_reversed)