问题描述:
括号问题:给长度不超过20的仅由’(’, ‘)’, ‘?‘的字符串,’?‘可替换为’(‘或’)’,问有多少种合法的括号序列。合法序列指符号串的括号可以配对。例: (??) 应输出 2 (因为(())和()()是2种合法序列)
输入样例1:
(??)
输出样例1:
2
输入样例2:
(???)
输出样例2:
0
样例解析:
(??)的有效序列:
① (())
② ()()
(???)的有效序列:
① ((()))
② (()())
③ (())()
④ ()(())
⑤ ()()()
Code:
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
string str;
int flag=1,sum=0;
bool brake(string temp){ //根据栈的后进先出的原则来判断当前的括号序列是否有效
stack<char>res;
for(int i=0;i<temp.length();i++){
if(res.empty()&&temp[i]==')')//栈空,temp的下一个却是)则此序列肯定不符合
return false;
if(temp[i]=='(')//字符 ( 入栈
res.push(temp[i]);
else//字符 ) 出栈
res.pop();
}
if(res.empty())
return true;
else
return false;
}
int isKH(int i,string temp,int flag){
if(i>temp.size())
return 0;
if(temp.find('?')==-1){//程序执行到此处说明temp字符串没有字符?了
if(brake(temp)){ //判断是否为有效序列
sum++;
}
return 1;
}
// ? 选择( 或者 )
if(temp[i]=='?'&&flag){
flag=0;
temp[i]='(';
}
if(temp[i]=='?'&&!flag){
temp[i]=')';
flag=1;
}
isKH(i+1,temp,1);
isKH(i+1,temp,0);
}
int main(){
cin>>str;
isKH(0,str,1);
cout<<sum/2;//程序得出的有效序列是两倍 所以需要除以2 此处bug未找到原因
return 0;
}