301. Remove Invalid Parentheses

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 ).

Example 1:

Input: "()())()"
Output: ["()()()", "(())()"]

Example 2:

Input: "(a)())()"
Output: ["(a)()()", "(a())()"]

Example 3:

Input: ")("
Output: [""]
// BFS
bool isValid(const string& str) {
    int cnt = 0;
    for (char ch : str) {
        if (ch == '(') ++cnt;
        else if (ch == ')' && --cnt < 0) return false;
    }
    return cnt == 0;
}
vector<string> removeInvalidParentheses(string s) {
    vector<string> res;
    unordered_set<string> visited({s});
    queue<string> q({s});
    bool found = false;
    while (!q.empty()) {
        string t = q.front(); q.pop();
        if (isValid(t)) {
            res.push_back(t);
            found = true;
        }
        if (found) continue;
        // Remove one char from the t string
        for (int i = 0; i < t.length(); ++i) {
            if (t[i] != '(' && t[i] != ')') continue;
            string new_str = t.substr(0, i) + t.substr(i + 1);
            if (!visited.count(new_str)) {
                q.push(new_str);
                visited.insert(new_str);
            }
        }
    }
    return res;
}

Last updated

Was this helpful?