Leetcode 301. 删除无效的括号 困难 bfs

301. 删除无效的括号

题目:

给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。

返回所有可能的结果。答案可以按 任意顺序 返回。

 

示例 1:

输入:s = "()())()"
输出:["(())()","()()()"]

 

思路:

删除字符串中的左右括号,使得字符串有效。

有效的定义就是左括号数量始终大于等于右括号。且两者总数目一致。

使用BFS,每次获取当前层的所有可能,如果存在有效字符串,则保存结果并返回当前层所有有效结果。

每层只在之前的基础上删掉一个括号。

使用unordered_set来过滤重复结果。

复制代码
class Solution {
public:
    vector<string> removeInvalidParentheses(string s) {
        vector<string> ret;
        unordered_set<string> cur_set;
        cur_set.insert(s);
        while(!cur_set.empty()){
            unordered_set<string> next_set;
            for(auto& str:cur_set){
                if(isValid(str)){
                    ret.push_back(str);
                }
            }
            if(!ret.empty()){
                return ret;
            }
            for(auto& str:cur_set){
                for(int i=0;i<str.size();++i){
                    if(i>0&&str[i]==str[i-1])
                        continue;
                    string next=str.substr(0,i)+str.substr(i+1,str.size());
                    next_set.insert(next);
                }
            }
            cur_set=next_set;
        }
        return ret;
    }
    bool isValid(string s){
        int left=0,right=0;
        for(auto& c:s){
            if(c=='(')
                left++;
            else if(c==')')
                right++;
            if(right>left)
                return false;
        }
        return left==right;
    }
};
复制代码

 

posted @   鸭子船长  阅读(55)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-03-18 Python操作redis系列之 列表(list) (五)(转)
2016-03-18 Android动画学习笔记-Android Animation
点击右上角即可分享
微信分享提示