试题描述:
输入
整数N
输出
N行组合
示例输入
1
2
3
0
示例输出
()
()()
(())
((()))
(()())
(())()
()(())
x小兰的大学教授要求小兰实现一个算法,打印n对(n>=0)括号中的全部有效组合(即左右括号正确的配对)。
要求输入一个整数n,输出若干行,每一行一个有效组合。
请你帮小兰完成这个算法。
输入
整数N
输出
N行组合
示例输入
1
2
3
0
示例输出
()
()()
(())
((()))
(()())
(())()
()(())
()()()
#include <string>
#include <iostream>
using namespace std;
void ArrayCount(int l,int r,int n,string s)
{
if(r==n)
{
//num++;
cout<<s<<endl;
return;
}
if(r==l)
{
s.append("(");
l++;
ArrayCount(l,r,n,s);
}
else//r<l
{
if(l==n)
{
s.append(")");
r++;
ArrayCount(l,r,n,s);
}
else
{
s.append("(");
l++;
ArrayCount(l,r,n,s);
s.pop_back();
l--;
s.append(")");
r++;
ArrayCount(l,r,n,s);
}
}
return;
}
int main()
{
//int num=0;
string s;
int n;
int a[10];
int i = 0;
while (1)
{
cin>>n;
if (n!=0)
{
a[i] = n;
i++;
}
else
{
a[i] = 0;
break;
}
}
int j=0;
while(a[j])
{
ArrayCount(0,0,a[j],s);
cout<<endl;
j++;
}
//system("pause");
return 1;
}