删除最小数目的无效括号,以使输入字符串有效。返回所有可能的结果。
注意:输入字符串可能包含除括号(和)以外的字母。
例如:
“()())()”-> [“()()()”,“(())()”]
“(a)())()”-> [“(a)( )()“,”(a())()“]
”)(“-> [”“]]
Java解决方案
通过使用DFS可以解决此问题。
public class Solution {
ArrayList result = new ArrayList();
int max=0;
public List removeInvalidParentheses(String s) {
if(s==null)
return result;
dfs(s, "", 0, 0);
if(result.size()==0){
result.add("");
}
return result;
}
public void dfs(String left, String right, int countLeft, int maxLeft){
if(left.length()==0){
if(countLeft==0 && right.length()!=0){
if(maxLeft > max){
max = maxLeft;
}
if(maxLeft==max && !result.contains(right)){
result.add(right);
}
}
return;
}
if(left.charAt(0)=='('){
dfs(left.substring(1), right+"(", countLeft+1, maxLeft+1);//keep (
dfs(left.substring(1), right, countLeft, maxLeft);//drop (
}else if(left.charAt(0)==')'){
if(countLeft>0){
dfs(left.substring(1), right+")", countLeft-1, maxLeft);
}
dfs(left.substring(1), right, countLeft, maxLeft);
}else{
dfs(left.substring(1), right+String.valueOf(left.charAt(0)), countLeft, maxLeft);
}
}}
最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。