You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classSolution():
defremoveInvalidParentheses(self, s):
self.res=set()
max_len=0self.dfs(0, [], s)
''' After all backtracking, postprocess to find out the least modification '''foreleinself.res:
max_len=max(max_len, len(ele))
final= []
foreleinself.res:
iflen(ele) ==max_len:
final.append(ele)
returnfinaldefdfs(self, index, temp, s):
''' backtracking all possible solution with no pruning for sake :param temp: list '''ifindex==len(s):
temp_s=''.join(temp)
ifself.isValid(temp_s):
self.res.add(temp_s)
returntemp.append(s[index])
self.dfs(index+1, temp, s)
temp.pop()
self.dfs(index+1, temp, s)
defisValid(self, s):
''' check if a pair of parenthesis is valid '''count=0forcharins:
ifchar=='(':
count+=1ifchar==')':
count-=1ifcount<0:
returnFalsereturncount==0
Activity
tech-cow commentedon Sep 19, 2019
最原始粗暴的方法,直接所有可能性的去找,会有非常多的冗余。
DFS Base Case
只要index到底了,就走一遍
isValid在主方程跑完DFS以后,对得到的答案进行最少更改的检查
Brute Force
tech-cow commentedon Sep 20, 2019
优化1.
Brute Force的冗余,通过Pruning去省去一些重复计算。
思考的方式可以从需要最少被更改几次出发
计算出左右括号的个数差,然后用函数
change_needed表示。 在Backtrack过程中,往temp里面增加元素的时候不需要更改这个函数,因为并没有删除任何函数,而在删减的过程中,减少这个函数。这种方式可以对change_needed为负数的时候进行剪枝
然后对左右括号和其他字符的区分,也进行了一边的剪枝。
优化代码
tech-cow commentedon Sep 20, 2019
优化2:
把Temp的Array 变成了 String,减少了一些代码和速度
tech-cow commentedon Feb 21, 2020
tech-cow commentedon Feb 24, 2020