#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
//n个括号的合法全排列.
bool Grial(char *str)
{
stack<char> st;
char *p = str;
while (*p != '\0')
{
if (*p == '(')
{
st.push(*p);
}
if (*p == ')')
{
if (st.empty() == true)
{
st.push(*p);
}
else if (st.top() == '(')
st.pop();
else return false;
}
p++;
}
return st.empty() != false;
}
void Grial(char * p,char * str,char *s,int x,int n)
{
if (x==n)
{
*str = '\0';
if (Grial(p))
cout << p << endl;
return;
}
for (int i = 0; i < 2; i++)
{
*str = s[i];
Grial(p,str+1, s,x+1,n);
}
}
int main()
{
char s[] = "()";
int n;
cout << "请输入括号个数:" << endl;
cin >> n;
if (n < 2 && n % 2 != 0)
{
cout << "你的输入有误" << endl;
return -1;
}
char *str = new char[n];
memset(str,'0',sizeof(str));
Grial(str,str,s,0,n);
return 0;
}
算法题:n个括号的合法全排列
最新推荐文章于 2022-04-18 20:13:24 发布