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())()"] ")(" -> [""]
解题思路:
1. 如果给我们一个字符串,首先去掉不合法的首字符即')'以及不合法的尾字符‘(’, 将其变为以‘(’开头,以‘)’结尾的字符串: (.......)
2. 对这个字符串,我们需要统计它有多少个不合法的‘(’,以及‘)’,分别用num1和num2表示。
3. batracking, 我们每次判断去掉一个字符后的字符串是否是合法字符串,是的话那么将该字符串存入结果字符,并递归回溯。 否则,继续处理。
class Solution {
public:
vector<string> removeInvalidParentheses(string& s) {
vector<string> ret;
int num1 = 0, num2 = 0, sum = 0;
int beg = 0, end = s.size()-1;
while(s[beg]==')') beg++;
while(s[end]=='(') end--;
s = s.substr(beg,end-beg+1);
for(int i=0 ;i<s.size();i++){
if(s[i]=='(') sum++;
else if(s[i]==')') sum--;
num2 = min(num2,sum);
}
num1 = sum - num2;
removeInvalidParentheses(s,0,num1,num2,ret);
return ret;
}
bool isValid(string s) {
int sum = 0;
for(auto &c : s) //check whether s is valid or not
{
if(c == '(') ++sum;
else if(c == ')') --sum;
if(sum < 0) return false;
}
return sum == 0;
}
void removeInvalidParentheses(string s,int beg, int num1, int num2, vector<string>& ret){
if(num1==0 && num2 == 0)
{
if(isValid(s))
ret.push_back(s);
return;
}
for(int i = beg; i < s.size(); ++i)
{
string tmp = s;
/*
The num2 == 0 expression is hard to come up with. All invalid '('
can only appear after invalid ')', otherwise
there is no invalid ')'. It's OK we don't add
this num2 == 0 test, without which only slows
down the performance a little bit, from 4ms to 12ms.
*/
if(num2 == 0 && num1 > 0 && tmp[i] == '(')
{
if(i == beg || tmp[i] != tmp[i - 1]) //Watch here! This is the trick to avoid duplicates.
{
tmp.erase(i, 1);
removeInvalidParentheses(tmp, i, num1 - 1, num2, ret);
}
}
if(num2 < 0 && tmp[i] == ')')
{
if(i == beg || tmp[i] != tmp[i - 1])
{
tmp.erase(i, 1);
removeInvalidParentheses(tmp, i, num1, num2 + 1, ret);
}
}
}
}
};