思路:BFS
代码:
class Solution {
public List<String> removeInvalidParentheses(String s) {
Set<String> set = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.add(s);
while(!queue.isEmpty()){
Set<String> next = new HashSet<>();
int size = queue.size();
for(int i=0;i<size;i++){
String str = queue.poll();
if(check(str)){
set.add(str);
}
if(set.isEmpty()){
for(int j=0;j<str.length();j++){
if(str.charAt(j)=='(' || str.charAt(j)==')'){
next.add(str.substring(0, j) + str.substring(j + 1));
}
}
}
}
queue.addAll(next);
}
return new ArrayList<>(set);
}
private boolean check(String s){
int count=0;
for(char c:s.toCharArray()){
if(c=='('){
count++;
}else if(c==')'){
count--;
}
if(count<0) return false;
}
return count==0;
}
}