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())()"] ")(" -> [""]
Credits:
Analysis: this question is quite similar to all the Parentheses question. we need to make sure that the left ( is more than ), then if the number of the left ( is equal to the number of the right one ), there is a valid parentheses. then we just compare is to the maxValue.
1 This problem has a trick that how to delete the duplicates. this is quite common in backtracking
if(i != start && s.charAt(i)== s.charAt(i - 1))
continue;
2 also consider the "", when the input string is "", we need to return a "" in the result
code
public class Solution {
int maxNum = 0;
public List<String> removeInvalidParentheses(String s) {
int left = 0;
int right = 0;
List<String> resultList = new ArrayList<String>();
resultList.add("");
int length = s.length();
if(length == 0){
return resultList;
}
int start = 0; //start is to record the begining bit to visit the String
dfs( s, "", start, left, right,resultList,0);
return resultList;
}
public void dfs(String s, String result, int start, int left, int right,List<String> resultList, int number){
if(left == right && number != 0){
if(number > maxNum){
maxNum = number;
resultList.clear();
resultList.add(result);
}
else if(number == maxNum){
resultList.add(result);
}
}
int length = s.length();
if(start >= length)
return;
for(int i = start; i < length; i++){
if(i != start && s.charAt(i)== s.charAt(i - 1))
continue;
if(s.charAt(i) == '(')
dfs(s,result + "(", i + 1, left + 1, right,resultList,number + 1);
else if(s.charAt(i) == ')' && left > right)
dfs(s,result + ")", i + 1, left, right + 1,resultList,number + 1);
else if(s.charAt(i) != '(' && s.charAt(i) != ')')
dfs(s,result + s.charAt(i),i + 1,left,right,resultList, number + 1);
}
}
}