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 )
.
Examples:
"() ()) ()", ["() () () ()", "(()) ()", "(a) ()) ()", "(a) () ()", "(a) () ()", "(A) (") ["]
Credits:
Special thanks to @hpplayer for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
This problem lets us remove the fewest parentheses so that the given string is a valid string with parentheses, we have parentheses in the small math, so we should be not unfamiliar with the legitimate string of parentheses, the number of left and right brackets in the string should be the same, and each closing parenthesis must have its corresponding left parenthesis. And the example given in the topic also shows that the removal method is not unique, we need to find out all the legal methods. Reference to the online God solution, the problem can first use BFS to solve, we first put a given string into the queue, and then take out to detect whether it is legitimate, if the legitimate direct return, illegal, our team to traverse, for the encounter of the left and right bracket character, we remove the bracket word Fuzhou into a new string, If this string has not been encountered before, queue it up, we use a hash table to record whether a string has occurred. We do the same thing for each element in the queue until the queue is empty and no valid string is found, so return to the empty set, see the code below:
classSolution { Public: Vector<string> removeinvalidparentheses (strings) {vector<string>Res; Unordered_map<string,int>visited; Queue<string>Q; Q.push (s); ++Visited[s]; BOOLFound =false; while(!Q.empty ()) {s=Q.front (); Q.pop (); if(IsValid (s)) {res.push_back (s); Found=true; } if(found)Continue; for(inti =0; I < s.size (); ++i) {if(S[i]! ='('&& S[i]! =')')Continue; stringt = s.substr (0, i) + s.substr (i +1); if(Visited.find (t) = =Visited.end ()) {Q.push (t); ++Visited[t]; } } } returnRes; } BOOLIsValid (stringt) {intCNT =0; for(inti =0; I < t.size (); ++i) {if(T[i] = ='(') ++CNT; if(T[i] = =')'&& cnt--= =0)return false; } returnCNT = =0; }};
This problem also has the solution of DFS (not to be continued ...) )
Similar topics:
Different Ways to Add parentheses
Longest Valid parentheses
Generate parentheses
Valid parentheses
Resources:
Https://leetcode.com/discuss/67842/share-my-java-bfs-solution
Https://leetcode.com/discuss/67825/backtracking-trick-here-eliminate-duplicates-without-map
Https://leetcode.com/discuss/67821/dfs-and-bfs-java-solutions
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Remove Invalid parentheses remove illegal parentheses