1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| class Solution { public: vector<string> removeInvalidParentheses(string s) { for(auto& ch : s) { if(ch == ')') { if(leftCount == 0) ++rightCount; else --leftCount; }else if(ch == '(') ++leftCount; } string tmp; helper(s, 0, s.size(), 0, 0, tmp); vector<string> ret(set.begin(), set.end()); return ret; } private: unordered_set<string> set; int leftCount = 0; int rightCount = 0; void helper(string& s, int index, int sz, int curLeft, int curRight, string& tmp) { if(index == sz) { if(leftCount == 0 && rightCount == 0) set.insert(tmp); return; } auto ch = s[index]; if(ch == '(' && leftCount) { --leftCount; helper(s, index + 1, sz, curLeft, curRight, tmp); ++leftCount; }else if(ch == ')' && rightCount) { --rightCount; helper(s, index + 1, sz, curLeft, curRight, tmp); ++rightCount; } tmp += ch; if(ch != ')' && ch != '(') helper(s, index + 1, sz, curLeft, curRight, tmp); else if(ch == ')' && curLeft > curRight) helper(s, index + 1, sz, curLeft, curRight + 1, tmp); else if(ch == '(') helper(s, index + 1, sz, curLeft + 1, curRight, tmp); tmp.pop_back(); } };
|