1
+ #include < string>
2
+ #include < unordered_set>
3
+ using namespace std ;
4
+
5
+ class Solution {
6
+ public:
7
+ vector<string> removeInvalidParentheses (string s) {
8
+ int left = 0 ;
9
+ int right = 0 ;
10
+ for (auto ch: s) {
11
+ if (ch == ' (' ) ++left;
12
+ if (ch == ' )' ) {
13
+ if (left > 0 ) --left;
14
+ else ++right;
15
+ }
16
+ }
17
+ vector<string> results;
18
+ unordered_set<string> unique;
19
+ DFS (s, 0 , 0 , left, right, " " , results, unique);
20
+ return results;
21
+ }
22
+
23
+ void DFS (string&s, int idx, int pair, int left, int right, string solution, vector<string>& results, unordered_set<string>& unique) {
24
+ if (idx == s.size ()) {
25
+ if (left == 0 && right == 0 && pair == 0 && unique.find (solution) == unique.end ()) {
26
+ results.push_back (solution);
27
+ unique.insert (solution);
28
+ }
29
+ return ;
30
+ }
31
+ if (s[idx] == ' (' ) {
32
+ if (left > 0 ) DFS (s, idx+1 , pair, left-1 , right, solution, results, unique);
33
+ DFS (s, idx+1 , pair+1 , left, right, solution+" (" , results, unique);
34
+ }else if (s[idx] == ' )' ) {
35
+ if (right > 0 ) DFS (s, idx+1 , pair, left, right-1 , solution, results, unique);
36
+ if (pair > 0 ) DFS (s, idx+1 , pair-1 , left, right, solution+" )" , results, unique);
37
+ }else {
38
+ DFS (s, idx+1 , pair, left, right, solution+s[idx], results, unique);
39
+ }
40
+ return ;
41
+ }
42
+ };
0 commit comments