Skip to content

Commit 7cb4d8f

Browse files
committed
backtrack
1 parent d9ec458 commit 7cb4d8f

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

301 Remove Invalid Parentheses.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""
2+
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
3+
4+
Note: The input string may contain letters other than the parentheses ( and ).
5+
6+
Examples:
7+
"()())()" -> ["()()()", "(())()"]
8+
"(a)())()" -> ["(a)()()", "(a())()"]
9+
")(" -> [""]
10+
11+
"""
12+
__author__ = 'Daniel'
13+
14+
15+
class Solution(object):
16+
def removeInvalidParentheses(self, s):
17+
"""
18+
:type s: str
19+
:rtype: List[str]
20+
"""
21+
n = len(s)
22+
# solve min count of removal
23+
cnt = 0
24+
l = 0
25+
for c in s:
26+
if c == "(":
27+
l += 1
28+
elif c == ")":
29+
l -= 1
30+
if l < 0:
31+
l = 0
32+
cnt += 1
33+
34+
cnt += l
35+
ret = []
36+
self.dfs(s, "", 0, None, 0, cnt, ret)
37+
return ret
38+
39+
def dfs(self, s, cur, l, removed, i, cnt, ret):
40+
"""backtracking, pre-check"""
41+
if l < 0 or cnt < 0 or i > len(s):
42+
return
43+
if i == len(s):
44+
if cnt == 0 and l == 0:
45+
ret.append(cur)
46+
return
47+
48+
if s[i] in ("(", ")"):
49+
# jump
50+
C = cnt
51+
while i < len(s) and removed and removed == s[i]:
52+
i += 1
53+
C -= 1
54+
55+
if C != cnt:
56+
self.dfs(s, cur, l, removed, i, C, ret)
57+
else:
58+
self.dfs(s, cur, l, s[i], i+1, cnt-1, ret)
59+
60+
L = l+1 if s[i] == "(" else l-1
61+
self.dfs(s, cur+s[i], L, None, i+1, cnt, ret) # put
62+
else:
63+
self.dfs(s, cur+s[i], l, None, i+1, cnt, ret)
64+
65+
66+
if __name__ == "__main__":
67+
assert Solution().removeInvalidParentheses("(a)())()") == ['(a())()', '(a)()()']
68+
69+
70+
71+

0 commit comments

Comments
 (0)