Just use BFS to solve this problem:

1. put the s to queue

2. if s is not a valid string, then remove a '(' or ')', and then put to the queue.

3. once find valid strings, return.

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        Set<String> res = new HashSet<>();
        Queue<String> queue = new LinkedList<>();
        queue.offer(s);
        Set<String> visited = new HashSet<>();
        visited.add(s);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0;i<size;i++){
                String str = queue.poll();
                if(isValid(str)){
                    res.add(str);
                }
                else{
                    for(int j=0;j<str.length();j++){
                        String temp = str.substring(0, j)+str.substring(j+1);
                        if(!visited.contains(temp)){
                            visited.add(temp);
                            queue.offer(temp);
                        }
                    }
                }
            }
            if(res.size()>0)
                return new ArrayList(res);
        }
        return new ArrayList(res);
    }
    
    private boolean isValid(String s){
        int count = 0;
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='(')
                count++;
            else if(s.charAt(i)==')'){
                if(count>0)
                    count--;
                else
                    return false;
            }
            
        }
        return count==0;
    }
}

 

posted on 2022-04-07 02:42  阳光明媚的菲越  阅读(27)  评论(0编辑  收藏  举报