您的位置:首页 > 其它

[LeetCode]Remove Invalid Parentheses

2017-07-07 16:07 330 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: