# 301. Remove Invalid Parentheses 去掉不合理的括号

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())()"]
")(" -> [""]


T(n) = n x C(n, n) + (n-1) x C(n, n-1) + ... + 1 x C(n, 1) = n x 2^(n-1).

class Solution {
public:
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;
}
return count == 0;
}

vector<string> removeInvalidParentheses(string s) {
set<string> sets;
vector<string>res;
queue<string>q;
q.push(s);
sets.insert(s);
bool found =false;
while(!q.empty()){
string str = q.front();
q.pop();
if(isvalid(str)){
res.push_back(str);
found = true;
}
if(found) continue;
for(int i = 0; i < s.size(); i++){
if(str[i] == '(' || str[i] == ')'){
string strs = str.substr(0,i) + str.substr(i+1);
if(sets.find(strs) == sets.end()){
sets.insert(strs);
q.push(strs);
}
}
}
}
return res;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：301. Remove Invalid Parentheses 去掉不合理的括号 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)