题目描述
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。
说明: 输入可能包含了除 (
和 )
以外的字符。
示例 1:
输入: "()())()" 输出: ["()()()", "(())()"]
示例 2:
输入: "(a)())()" 输出: ["(a)()()", "(a())()"]
示例 3:
输入: ")(" 输出: [""]
问题分析
此题用宽度优先搜索(BFS)。创建一个队列,用来层序遍历。创建一个哈希set,用来防止将重复的字符串加入队列。层序遍历的第一层是给定字符串,第二层是给定字符串分别在不同位置上去掉一个左括号或右括号,第三层以此类推。每次在队列弹出元素后,判断这个弹出的字符串是否为有效的,如果是,那么将变量found记为true,然后将此字符串加入答案数组ans。由于我们只要删除最小数量的括号的答案,所以当这一层遍历结束后,就不要再往下遍历了,因为下面层开始就删除更多数量的括号了,所以我们要在这一层结束后立即break跳出循环,然后返回答案数组ans。
代码实现
class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
vector<string> ans;
queue<string> q;
q.push(s);
unordered_set<string> visited;
visited.insert(s);
bool found = false;
while(!q.empty()){
for(int i = q.size(); i > 0; i--){
string temp = q.front();
q.pop();
if(isvalid(temp)){
found = true;
ans.push_back(temp);
}
for(int i = 0; i < temp.size(); i++){
if(temp[i] != '(' && temp[i] != ')')
continue;
string str = temp.substr(0, i) + temp.substr(i + 1);
if(!visited.count(str)){
q.push(str);
visited.insert(str);
}
}
}
if(found)
break;
}
return ans;
}
bool isvalid(string s){
int count = 0;
for(char c : s){
if(c == '(')
count++;
else if(c == ')'){
count--;
if(count < 0)
return false;
}
}
return count == 0;
}
};