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())()"] ")(" -> [""]
class Solution {
public:
void dfs(string &s,vector<string>&result,string str,int l,int r,int cnt,int start){
if(l == r && l==cnt){
for(int i = start;i < s.size();i++){
if(s[i] != '(' && s[i] != ')')
str.append(1,s[i]);
}
for(int k = 0;k < result.size();k++){
if(str == result[k])return;
}
result.push_back(str);
return;
}
for(int i = start;i < s.size();i++){
if(s[i]=='('){
if(l < cnt)dfs(s,result,str+'(',l+1,r,cnt,i+1);
}else if(s[i]==')'){
if(l > r)dfs(s,result,str+')',l,r+1,cnt,i+1);
}else{
str.append(1,s[i]);
dfs(s,result,str,l,r,cnt,i+1);
}
}
}
/*algorithm: DFS
*/
vector<string> removeInvalidParentheses(string s) {
//compute minium pair count
int l = 0,r = 0;
for(int i = 0;i < s.size();i++){
if(s[i]=='(')l++;
else if(s[i]==')'&&l>r)r++;
}
vector<string>result;
dfs(s,result,"",0,0,min(l,r),0);
return result;
}
};