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())()"] ")(" -> [""]class Solution { public: vector<string> removeInvalidParentheses(string s) { set<string> temp; int n = s.length(); int left_remove = 0; int right_remove = 0; for (int i = 0; i < n; i++) { if (s[i] == '(') { left_remove++; } else if (s[i] == ')') { if (left_remove > 0) { left_remove--; } else { right_remove++; } } } visit(s, n, 0, left_remove, right_remove, 0, 0, "", temp); vector<string> result(temp.begin(), temp.end()); return result; } private: void visit(string &s, int n, int pos, int left_remove, int right_remove, int left_count, int right_count, string buf, set<string> &temp) { if (n == pos) { if (left_remove == 0 && right_remove == 0) { temp.insert(buf); } return; } if (s[pos] == '(') { if (left_remove > 0) { visit(s, n, pos+1, left_remove-1, right_remove, left_count, right_count, buf, temp); } visit(s, n, pos+1, left_remove, right_remove, left_count+1, right_count, buf+s[pos], temp); } else if (s[pos] == ')') { if (right_remove > 0) { visit(s, n, pos+1, left_remove, right_remove-1, left_count, right_count, buf, temp); } if (left_count <= right_count) { return; } visit(s, n, pos+1, left_remove, right_remove, left_count, right_count+1, buf+s[pos], temp); } else { visit(s, n, pos+1, left_remove, right_remove, left_count, right_count, buf+s[pos], temp); } } };