주어진 괄호 시퀀스; 이제 잘못된 괄호를 제거하여 만들 수 있는 모든 괄호를 인쇄해야 합니다. 예를 들면
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++ 프로그램과 이 문제를 해결하기 위한 완전한 접근 방식(Normal)을 배웠습니다. C, Java, python 및 기타 언어와 같은 다른 언어로 동일한 프로그램을 작성할 수 있습니다. 이 튜토리얼이 도움이 되기를 바랍니다.