Remove Invalid Parentheses
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) (") ["]
https://leetcode.com/problems/remove-invalid-parentheses/ (and) always in pairs, appearing in (previous) meaningless. The open variable Countleft record has not yet been matched (the number of times. Three cases per round of cycle: 1. (, can choose to take or not to take, 2.), if there is no match (, you can choose to take or not to take, otherwise you can only not take; 3. Take the other letters directly. Because you want to remove the fewest parentheses, the open variable Maxleft record has a maximum of several pairs of parentheses, that is, there are a few matching successes (. Notice the order of the two sentences:
DFS (str.substring (1), Subres + ' (', Countleft + 1, maxleft + 1);
DFS (str.substring (1), Subres, Countleft, maxleft);
The result of matching parentheses is guaranteed to appear in the result array first, without omitting the result.
Https://leetcode.com/discuss/68272/straight-forward-solution-with-explanation
1 /**2 * @param {string} s3 * @return {string[]}4 */5 varRemoveinvalidparentheses =function(s) {6 varres = [], max = 0;7DFS (S, "", 0, 0);8 returnRes.length!== 0? Res: [""];9 Ten functiondfs (str, subres, Countleft, maxleft) { One if(str = = = ""){ A if(Countleft = = = 0 && subres!== ""){ - if(Maxleft >max) -Max =Maxleft; the if(max = = Maxleft && res.indexof (subres) = = = 1) - Res.push (subres); - } - return; + } - if(Str[0] = = = ' ('){ +DFS (str.substring (1), Subres + ' (', Countleft + 1, Maxleft + 1); ADFS (str.substring (1), Subres, Countleft, maxleft); at}Else if(Str[0] = = = ') '){ - if(Countleft > 0) -DFS (str.substring (1), Subres + ') ', countLeft-1, maxleft); -DFS (str.substring (1), Subres, Countleft, maxleft); -}Else{ -DFS (str.substring (1), Subres + str[0], Countleft, maxleft); in } - } to};
[Leetcode] [JavaScript] Remove Invalid Parentheses