方法采用BFS ,注意因为是返回所有可能情况,所以对于出答案的那轮要遍历完。
class Solution {
public:
unordered_set<string> candidates;
int removeMax=INT_MAX;
bool isValid(string s){
int n=s.size();
int count=0;
for(int i=0;i<n;i++){
if(s[i]=='(')
count++;
else if(s[i]==')'){
count--;
if(count<0)
return false;
}
}
return count==0;
}
vector<string> removeInvalidParentheses(string s) {
queue<pair<string,int>> Q;
unordered_map<string,bool> visited;
Q.emplace(s,0);
while(!Q.empty()){
int n=Q.size();
for(int i=0;i<n;i++){
auto cur=Q.front();
Q.pop();
string sc=cur.first;
int remove=cur.second;
visited[sc]=true;
int m=sc.size();
if(isValid(sc)){
if(remove==removeMax){
candidates.insert(sc);
continue;
}
else if(remove<removeMax){
candidates.clear();
candidates.insert(sc);
removeMax=remove;
continue;
}
}
for(int i=0;i<m;i++){
if(sc[i]=='('||sc[i]==')'){
string cand="";
if(i>0) cand+=sc.substr(0,i);
if(i<m-1) cand+=sc.substr(i+1,m-1);
if(visited[cand]==0){
Q.emplace(cand,remove+1);
visited[cand]=true;
}
}
}
}
if(removeMax<INT_MAX&&candidates.size()>0)
break;
}
vector<string> res(candidates.begin(),candidates.end());
return res;
}
};
}
vector<string> res(candis.begin(),candis.end());
return res;
}
};