leetcode+移除最少的括号到合理,BFS+hash记录visit

https://leetcode.com/problems/remove-invalid-parentheses/description/

class Solution {
public:
    bool isvalid(string t)
    {
        int cnt = 0;
        for(int i=0; i < t.size(); i++){
            if(t[i]=='(') cnt++;
            else if(t[i]==')' && --cnt<0) return false;
        }
        return cnt==0;
    }
    vector<string> removeInvalidParentheses(string s) {
        vector<string> res;
        set<string> vis;
        vis.insert(s);
        queue<string> Q;
        Q.push(s);
        bool found = false;
        string t;
        while (!Q.empty()) {
            t = Q.front(); Q.pop();
            if(isvalid(t)){
                res.push_back(t);
                found = true;
            }
            if(found) continue;
            for(int i=0; i<t.size(); i++){
                if(t[i] !='(' && t[i]!=')') continue;
                string str = t.substr(0,i) + t.substr(i+1); //删除了t[i]元素
                if(!vis.count(str)){
                    Q.push(str);
                    vis.insert(str);
                }
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/81154038
今日推荐