301. Remove Invalid Parentheses
這題很好,BFS的想法很奇特混狠,去除最少的元素使得新的string合法,也就是說從不合法的s,找到所有最短路徑(刪除一個(gè)值就相當(dāng)于一條邊)的合法的new_s纷铣。解法就是把每一次刪除的所有可能性列舉出來矢渊,然后挨個(gè)挨個(gè)的檢測(cè)。
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
level = {s}
while True:
valid = filter(self.isvalid, level)
if valid:
return valid
level = {s[:i] + s[i+1:] for s in level for i in range(len(s))}
def isvalid(self, s):
ctr = 0
for c in s:
ctr += (c == '(') - (c == ')')
if ctr < 0:
return False
return ctr == 0