[LeetCode] 301. Remove Invalid Parentheses_Hard tag:BFS

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Note: The input string may contain letters other than the parentheses ( and ).

Example 1:

Input: "()())()"
Output: ["()()()", "(())()"]

Example 2:

Input: "(a)())()"
Output: ["(a)()()", "(a())()"]

Example 3:

Input: ")("
Output: [""]

这个题目的思路参考地址,是用Java写的, 不得不说, 太牛逼了.

主要思路我理解为, 利用Count去看一个valid parentheses, 然后一旦发现不是valid的时候, 那么我们就在目前的部分string里面, 分别将 ')' 去掉一个, 但是这样会出现的问题是我们可能有重复的情况, 比如说s = ()), we can remove s[1] or s[2] but the result is the same (). Thus, we restrict ourself to remove the first ) in a series of concecutive )s.

那么去掉多余的')' 之后, prefix 变成valid, 然后再recursively call 剩下的string, 但是我们只需要再从上次remove掉的那个位置开始检测即可,否则的话又有重复的. For this, we keep tracking the last removal position and only remove ‘)’ after that.

以上的做法就是去掉多余的')', 比如"()()())", 但是没有办法解决"()()("这样的情况, 那么思路类似,就是将以上的做法, 从右向左走一遍, 然后count计数的时候调换下顺序即可, 但是这个思路牛逼的地方就是,它将s reverse, 然后还是用原来的code, 只是加多一个parameter pairs即可. 实在是太牛逼了. 如果还是看不懂的话建议去看上面参考地址的解释, 很详细, 都是英文, 但是解释的肯定比我好, 比我清楚. 不得不再说一次, 真的太腻害了!

1. Constraints

1) s可以为empty

2) 每个元素可以是除了"()"之外的元素

2. Idea

利用所谓的recursive helper function 去帮忙, 不知道时间复杂度是多少.

3.Code:

 1 class Solution:
 2     def removeInvalidParentheses(self, s):
 3         def helper(s, ans, prei, prej, pairs):
 4             count = 0
 5             for i in range(prei, len(s)):
 6                 if s[i] == pairs[0]: count += 1
 7                 if s[i] == pairs[1]: count -= 1
 8                 if count >= 0: continue
 9                 for j in range(prej, i+1): # note it is i+1, because until i
10                     if s[j] == pairs[1] and (j == prej or s[j-1] != s[j]):
11                         helper(s[:j] + s[j+1:], ans, i, j, pairs)
12                 return 
13             revs = s[::-1]
14             if pairs[0] == '(':
15                 helper(revs, ans, 0, 0, ")(")
16             else:
17                 ans.append(revs)
18     ans = []
19     helper(s, ans, 0, 0, "()")
20     return ans

4. Test cases

1) ""

2) "()"

3) "())"

4) "(()"

5) 

"()())()"

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9282626.html