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;
}
};