题目描述:
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 )
.
Example 1:
Input: "()())()"
Output: ["()()()", "(())()"]
Example 2:
Input: "(a)())()"
Output: ["(a)()()", "(a())()"]
Example 3:
Input: ")("
Output: [""]
给定一个字符串,包含‘(’和‘)’和其他字符,求出除去最少的字符使得括号匹配的所有可能的字符串。首先需要计算最少需要除去多少个左括号和右括号,然后调用递归,并且在除去了最少数目的字符之后再判断得到的结果是否为合法的括号匹配。
class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
vector<string> result;
int left=0;
int right=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(') left++;
else if(s[i]==')')
{
if(left==0) right++;
else left--;
}
}
get_valid_parentheses(s,0,left,right,result);
return result;
}
void get_valid_parentheses(string s, int i, int left, int right, vector<string>& result)
{
if(left<0||right<0) return;
else if(left==0&&right==0)
{
if(isValid(s)) result.push_back(s);
return;
}
for(int j=i;j<s.size();j++)
{
string temp=s;
if(j>0&&s[j]==s[j-1]) continue;
else if(s[j]=='('&&left>0)
get_valid_parentheses(temp.erase(j,1),j,left-1,right,result);
else if(s[j]==')'&&right>0)
get_valid_parentheses(temp.erase(j,1),j,left,right-1,result);
}
}
bool isValid(string s)
{
int count=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(') count++;
else if(s[i]==')') count--;
if(count<0) return false;
}
if(count==0) return true;
else return false;
}
};