Leetcode Hot100 第38题 301.删除无效的括号

class Solution {
public:
    int len=0;
    int max_score=0;
    unordered_set<string> hash;
    int n=0;
    vector<string> removeInvalidParentheses(string s) {
        int l=0, r=0;// l代表需要删除的左括号数量,r代表需要删除的右括号数量
        n = s.size();
        int right=0,left=0;// 为了剪枝,合理的字符串中最多出现多少个左括号
        for(char c:s){
            if(c=='('){
                l++;
                left++;
            }else if(c==')'){
                if(l!=0) l--;
                else r++;
                right++;
            }
        }
        len = n - l - r;// 删除掉不合法的括号后,最后字符串的长度
        max_score = min(left,right);
        dfs(s,"",0,0,l,r);
        return {hash.begin(),hash.end()};
    }
    void dfs(string s, string res, int score, int index, int l, int r){
        if(res.size()==len&&score==0){
            hash.insert(res);
            return;
        }
        if(index==n) return;
        if(score<0||score>max_score) return; //剪枝一
        if(l<0||r<0) return; //剪枝二
        char c = s[index];
        if(c=='('){
            dfs(s, res+c, score+1, index+1, l, r);
            dfs(s, res, score, index+1, l-1, r);
        }else if(c==')'){
            dfs(s, res+c, score-1, index+1, l, r);
            dfs(s, res, score, index+1, l, r-1);
        }else{
            dfs(s, res+c, score, index+1, l, r);
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值