1. 程式人生 > >Remove Invalid Parentheses

Remove Invalid Parentheses

解法一:recursion DFS

class Solution {
public:
    bool isvalid(string& s){
        int l=0;
        for(char c:s){
            if(c=='(') l++;
            else if(c==')'){
                l--;
                if(l<0) return false;
            }
        }
        //return l==0;
        return true;
    }
    void helper(string s, int start, int lcnt, int rcnt, vector<string>& res){
        if(lcnt==0 && rcnt==0) {
            if(isvalid(s)) {
                res.push_back(s);
            }
            return;
        }
        for(int i=start;i<s.size();i++){
            if(i!=start && s[i]==s[i-1]) continue;
            if(lcnt>0 && s[i]=='(')
                helper(s.substr(0,i)+s.substr(i+1), i, lcnt-1, rcnt, res);
            if(rcnt>0 && s[i]==')')
                helper(s.substr(0,i)+s.substr(i+1), i, lcnt, rcnt-1, res);
        }
    }
    vector<string> removeInvalidParentheses(string s) {
        int lcnt = 0;
        int rcnt = 0;
        for(char a:s){
            if(a=='(') lcnt++;
            else if(a==')'){
                if(lcnt>0) lcnt--;
                else rcnt++;
            }
        }
        vector<string> res;
        helper(s, 0, lcnt, rcnt, res);
        return res;
    }
};

Notes

1.刪除多餘的括號就行

2.在只有一種parentheses的情況,check if valid 可以用一個variable來代替stack

解法二:non-recursion BFS

class Solution {
public:
    bool isvalid(string& s){
        int l=0;
        for(char c:s){
            if(c=='(') l++;
            else if(c==')'){
                l--;
                if(l<0) return false;
            }
        }
        return l==0;
    }

    vector<string> removeInvalidParentheses(string s) {
        vector<string> res;
        queue<string> q;
        set<string> visited;
        bool found = false;
        visited.insert(s);
        q.push(s);
        while(!q.empty()){
            string 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 tt = t.substr(0,i)+t.substr(i+1);
                if(!visited.count(tt)){
                    q.push(tt);
                    visited.insert(tt);
                }   
            }
        }
        return vector<string>(res.begin(), res.end());
    }
};

Notes

1.set<string> visited - solve the problem of memory limit exceeded