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())()"] ")(" -> [""]
解题过程:
用BFS,因为这样的话,对于一个初始s,遍历它,并减去一个不合理的符号,得到的第一层就是全是n-1长度的,当减去一些后得到一个合理的字符串时,停止剪。那么这个层数就是减去的个数也是最小减去个数得到的结果。
当root层时s有长度n,则到第二层时,有c(n,n-1)个长度为n-1的子串,同时进行验证是时间为O(n-1),因此第一层的时间复杂度为O(n-1)*c(n,n-1);同理第二层的时间复杂度为O(n-2)*c(n-1,n-2)。。。。
一共的时间复杂度为
T(n)
= n
x C(n, n)
+ (n-1)
x C(n, n-1)
+ ... + 1
x C(n, 1)
= n
x 2^(n-1)
.
注意下面代码有个地方要注意:
就是当验证到正确的字符串时,要使found等于true,因为这样的话,就等于不用再对队列中的字符串进行剪了,只要把队列中剩下的字符串进行验证就行了。
开始时,我将continue写到if(isvalid(str))的范围里了,这样的话,当队列中的其他字符串取出进行验证发现不正确时,还会继续往下减,这样就不对了,因为已经得到了进行最少步剪的步数的到的结果了。
代码如下:
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;
}
};