- 有点类似leetcode.301题,删除无效括号
- 此题也可以使用DFS,但是因为题中好像有一句最少增加,所以考虑使用BFS,一层层遍历,直到存在有效括号
- 代码:
MOD = 10000007
s = input()
level = {s}
def isValid(string):
count = 0
for si in string:
if si == '(':
count += 1
elif si == ')':
count -= 1
if count < 0:
return False
return count == 0
while True:
Valid = list(filter(isValid, level))
if Valid:
print(len(Valid) % MOD)
break
next_level = set()
for item in level:
for i in range(len(item)+1):
next_level.add(item[:i] + '(' + item[i:])
next_level.add(item[:i] + ')' + item[i:])
- 记得当时是能够运行出结果的,但是时间复杂度来不及考虑了,望路过的大佬指正!!!