
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;
}Input : (v)())() Output : (v())()
在上述方法中,我们逐个移除括号,同时我们还会跟踪之前的序列,以避免重复检查相同的序列。如果我们找到了一个有效的序列,我们会打印出所有有效的可能性,这就是我们程序的执行过程。
立即学习“C++免费学习笔记(深入)”;
在本教程中,我们解决了一个查找并移除无效括号的问题。我们还学习了解决这个问题的C++程序和完整的解决方法(普通方法)。我们可以用其他语言如C、Java、Python和其他语言编写相同的程序。希望本教程对您有所帮助。
以上就是C++ 从表达式中删除无效的括号的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号