1
+ class Solution {
2
+ public List <String > removeInvalidParentheses (String s ) {
3
+ List <String > output = new ArrayList <>();
4
+ removeHelper (s , output , 0 , 0 , '(' , ')' );
5
+ return output ;
6
+ }
7
+
8
+ public void removeHelper (String s , List <String > output , int iStart , int jStart , char openParen , char closedParen ) {
9
+ int numOpenParen = 0 , numClosedParen = 0 ;
10
+ for (int i = iStart ; i < s .length (); i ++) {
11
+ if (s .charAt (i ) == openParen ) numOpenParen ++;
12
+ if (s .charAt (i ) == closedParen ) numClosedParen ++;
13
+ if (numClosedParen > numOpenParen ) { // We have an extra closed paren we need to remove
14
+ for (int j = jStart ; j <= i ; j ++) // Try removing one at each position, skipping duplicates
15
+ if (s .charAt (j ) == closedParen && (j == jStart || s .charAt (j - 1 ) != closedParen ))
16
+ // Recursion: iStart = i since we now have valid # closed parenthesis thru i. jStart = j prevents duplicates
17
+ removeHelper (s .substring (0 , j ) + s .substring (j + 1 , s .length ()), output , i , j , openParen , closedParen );
18
+ return ; // Stop here. The recursive calls handle the rest of the string.
19
+ }
20
+ }
21
+ // No invalid closed parenthesis detected. Now check opposite direction, or reverse back to original direction.
22
+ String reversed = new StringBuilder (s ).reverse ().toString ();
23
+ if (openParen == '(' )
24
+ removeHelper (reversed , output , 0 , 0 , ')' ,'(' );
25
+ else
26
+ output .add (reversed );
27
+ }
28
+ }
0 commit comments