[LeetCode]Remove Invalid Parentheses

来源:互联网 发布:网络机顶盒检测 编辑:程序博客网 时间:2024/06/10 08:56

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Note: The input string may contain letters other than the parentheses ( and ).

Examples:

"()())()" -> ["()()()", "(())()"]"(a)())()" -> ["(a)()()", "(a())()"]")(" -> [""]

public class Solution {     public List<String> removeInvalidParentheses(String s) {   dfs(0,0,0,s);   if(re.isEmpty()) re.add("");   return new ArrayList<String>(re);    }    HashSet<String> re=new HashSet<String>();    StringBuffer sb=new StringBuffer();    int max=0;    public void dfs(int k,int left,int right,String s){   if(k==s.length()){   if(right==left){   if(left*2==max) re.add(sb.toString());   else if(left*2>max){   max=left*2;   re.clear();   re.add(sb.toString());   }   }   return;   }   char ch=s.charAt(k);   sb.append(s.charAt(k));   if(ch=='('){       dfs(k+1,left+1,right,s);   }else if(ch==')'){   if(left>right) dfs(k+1,left,right+1,s);   }else{       dfs(k+1,left,right,s);   }   sb.deleteCharAt(sb.length()-1);   if(ch=='('||ch==')') dfs(k+1,left,right,s);    }}