301. Remove Invalid Parentheses 去掉不合理的括号

113 篇文章 0 订阅

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

Examples:

"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]


解题过程:

用BFS,因为这样的话,对于一个初始s,遍历它,并减去一个不合理的符号,得到的第一层就是全是n-1长度的,当减去一些后得到一个合理的字符串时,停止剪。那么这个层数就是减去的个数也是最小减去个数得到的结果。

当root层时s有长度n,则到第二层时,有c(n,n-1)个长度为n-1的子串,同时进行验证是时间为O(n-1),因此第一层的时间复杂度为O(n-1)*c(n,n-1);同理第二层的时间复杂度为O(n-2)*c(n-1,n-2)。。。。

一共的时间复杂度为 

T(n) = n x C(n, n) + (n-1) x C(n, n-1) + ... + 1 x C(n, 1) = n x 2^(n-1).


注意下面代码有个地方要注意:

就是当验证到正确的字符串时,要使found等于true,因为这样的话,就等于不用再对队列中的字符串进行剪了,只要把队列中剩下的字符串进行验证就行了。

开始时,我将continue写到if(isvalid(str))的范围里了,这样的话,当队列中的其他字符串取出进行验证发现不正确时,还会继续往下减,这样就不对了,因为已经得到了进行最少步剪的步数的到的结果了。


代码如下:


class Solution {
public:
    bool isvalid(string s){
        int count = 0;
        for(int i = 0; i < s.size(); i++){
            if(s[i] == '(')
            count++;
            else if(s[i] == ')')
            count--;
            if(count < 0)
            return false;
        }
        return count == 0;
    }

    vector<string> removeInvalidParentheses(string s) {
        set<string> sets;
        vector<string>res;
        queue<string>q;
        q.push(s);
        sets.insert(s);
        bool found =false;
        while(!q.empty()){
            string str = q.front();
            q.pop();
            if(isvalid(str)){
                res.push_back(str);
                found = true;
            }
            if(found) continue;
            for(int i = 0; i < s.size(); i++){
                if(str[i] == '(' || str[i] == ')'){
                    string strs = str.substr(0,i) + str.substr(i+1);
                    if(sets.find(strs) == sets.end()){
                        sets.insert(strs);
                        q.push(strs);
                    }
                }
            }
        }
        return res;
    }
};




  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值