Leetcode-301

Remove Invalid Parentheses

 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
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <vector>
#include <cstring>
#include <unordered_set>

class Solution {
    int rmPar(std::string& str) {
        int lrm = 0, rrm = 0;
        for (auto& c : str) {
            if (c == '(') {
                ++lrm;
            }
            if (c == ')') {
                if (lrm > 0) {
                    --lrm;
                }
                else {
                    ++rrm;
                }
            }
        }
        return lrm + rrm;
    }
    
public:
    std::vector<std::string> removeInvalidParentheses(std::string s) {
        std::vector<std::string> res;
        int n = rmPar(s);
        if (n == 0) {
            res.push_back(s);
            return res;
        }
        std::queue<std::pair<std::string, int>> q;
        q.push({s, n});
        std::unordered_set<std::string> visited;
        
        while (!q.empty()) {
            std::string s = q.front().first;
            n = q.front().second;
            q.pop();
            for (int i = 0; i < s.length(); ++i) {
                std::string next = s;
                next.erase(i, 1);
                if (visited.count(next)) {
                    continue;
                }
                visited.insert(next);
                int nn = rmPar(next);
                if (nn >= n) {
                    continue;
                }
                if (nn == 0) {
                    res.push_back(next);
                }
                else {
                    q.push({next, nn});
                }
            }
        }
        return res;
    }
};

Leetcode-301

Licensed under CC BY-NC-SA 4.0