-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path301. Remove Invalid Parentheses.py
45 lines (40 loc) · 1.15 KB
/
301. Remove Invalid Parentheses.py
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
44
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
def isvalid(s):
cnt = 0
for c in s:
if c == '(':
cnt += 1
if c == ')':
cnt -= 1
if cnt < 0:
return False
return cnt == 0
def dfs(s, st, l, r):
if l == 0 and r == 0:
if isvalid(s):
self.ans.append(s)
return
for i in range(st, len(s)):
if i - 1 >= st and s[i] == s[i - 1]:
continue
if r > 0 and s[i] == ')':
dfs(s[:i] + s[i + 1:], i, l, r - 1)
if l > 0 and s[i] == '(':
dfs(s[:i] + s[i + 1:], i, l - 1, r)
self.ans = []
l = r = 0
for c in s:
if c == '(':
l += 1
if c == ')':
if l == 0:
r += 1
else:
l -= 1
dfs(s, 0, l, r)
return self.ans