Catalogue
Best First Search
- Init state
- expansion/generation rule
- termination
301. Remove Invalid Parentheses
- BFS - level order traversal
- remove the minimum number
Solution1. BFS
1 | class Solution(object): |
- We can also use dfs with pruning to solve this problem!
Solution2. DFS + pruning
- Backtracking
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
32class Solution(object):
def removeInvalidParentheses(self, s):
lp = rp = 0
for ch in s:
if ch == '(':
lp += 1
elif ch == ')':
if lp > 0:
lp -= 1
else:
rp += 1
res = set()
self.dfs(lp, rp, 0, s, [], res)
return list(res)
def dfs(self, lp, rp, pairs, s, path, res):
if lp < 0 or rp < 0 or pairs < 0:
return
if len(s) == 0:
if lp == 0 and rp == 0 and pairs == 0:
res.add(''.join(path))
return
if s[0] == '(':
self.dfs(lp-1, rp, pairs, s[1:], path, res)
self.dfs(lp, rp, pairs+1, s[1:], path + [s[0]], res)
elif s[0] == ')':
self.dfs(lp, rp-1, pairs, s[1:], path, res)
self.dfs(lp, rp, pairs-1, s[1:], path + [s[0]], res)
else:
self.dfs(lp, rp, pairs, s[1:], path + [s[0]], res)