void dfs(string str, int level, int removeLevel, int cnt, pair<char, char> par) {
if (level == str.length()) {
string temp = str;
reverse(temp.begin(), temp.end());
if (par.first == '(') {
dfs(temp, 0, 0, 0, {')', '('});
} else {
results.push_back(temp);
}
return;
}
if (str[level] == par.first) {
dfs(str, level + 1, removeLevel, cnt + 1, par);
} else if (str[level] == par.second) {
cnt--;
if (cnt < 0) {
for (int j = removeLevel; j <= level; j++) {
if (str[j] == par.second && (j == removeLevel || str[j - 1] != par.second)) {
dfs(str.substr(0, j) + str.substr(j + 1), level, j, 0, par);
}
}
} else {
dfs(str, level + 1, removeLevel, cnt, par);
}
} else {
dfs(str, level + 1, removeLevel, cnt, par);
}
}
vector<string> results;
vector<string> removeInvalidParentheses(string str) {
dfs(str, 0, 0, 0, {'(', ')'});
return results;
}