Given a parentheses sequence; now, you have to print all the possible parentheses that it can make by removing the invalid brackets, for example
'Input : str = “()())()” -
Output : ()()() (())()
There are two possible solutions
"()()()" and "(())()"
Input : str = (v)())()
Output : (v)()() (v())()
在这个问题中,我们将使用回溯法来打印出所有有效的序列。
解决方案的方法
在这个方法中,我们将尝试使用BFS逐个移除开放和闭合括号。现在对于每个序列,我们检查它是否有效。如果有效,则将其打印为输出。
示例
'
#include <bits/stdc++.h>
using namespace std;
bool isParenthesis(char c){
return ((c == '(') || (c == ')'));
}
bool validString(string str){
// cout << str << " ";
int cnt = 0;
for (int i = 0; i < str.length(); i++){
if (str[i] == '(')
cnt++;
else if (str[i] == ')')
cnt--;
if (cnt < 0)
return false;
}
// cout << str << " ";
return (cnt == 0);
}
void validParenthesesSequences(string str){
if (str.empty())
return ;
set<string> visit; // if we checked that sting so we put it inside visit
// so that we will not encounter that string again
queue<string> q; // queue for performing bfs
string temp;
bool level;
// pushing given string as starting node into queue
q.push(str);
visit.insert(str);
while (!q.empty()){
str = q.front(); q.pop();
if (validString(str)){
// cout << "s";
cout << str << "n"; // we print our string
level = true; // as we found the sting on the same level so we don't need to apply bfs from it
}
if (level)
continue;
for (int i = 0; i < str.length(); i++){
if (!isParenthesis(str[i])) // we won't be removing any other characters than the brackets from our string
continue;
temp = str.substr(0, i) + str.substr(i + 1); // removing parentheses from the strings one by one
if (visit.find(temp) == visit.end()) { // if we check that string so we won't check it again
q.push(temp);
visit.insert(temp);
}
}
}
}
int main(){
string s1;
s1 = "(v)())()";
cout << "Input : " << s1 << "n";
cout << "Output : ";
validParenthesesSequences(s1);
return 0;
}
Output
'Input : (v)())()
Output : (v())()
上述代码的解释
在上述方法中,我们逐个移除括号,同时我们还会跟踪之前的序列,以避免重复检查相同的序列。如果我们找到了一个有效的序列,我们会打印出所有有效的可能性,这就是我们程序的执行过程。
结论
在本教程中,我们解决了一个查找并移除无效括号的问题。我们还学习了解决这个问题的C++程序和完整的解决方法(普通方法)。我们可以用其他语言如C、Java、Python和其他语言编写相同的程序。希望本教程对您有所帮助。