运行结果如下
5 //测试组数
1
()
1对应的卡特兰个个数为1
2
(())
()()
2对应的卡特兰个个数为2
2
(())
()()
2对应的卡特兰个个数为2
3
((()))
(()())
(())()
()(())
()()()
3对应的卡特兰个个数为5
4
(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())(())
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()
4对应的卡特兰个个数为14
import java.util.Scanner;
public class 括号卡特 {
static int count=0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn=new Scanner(System.in);
int len=scn.nextInt();
while(len-->0)
{
count=0;
int temp=scn.nextInt();
char a[]=new char[2*temp+1];
fun(2*temp,0,0,a);
System.out.println(temp+"对应的卡特兰个个数为"+count);
}
}
private static void fun(int n,int r,int l,char c[]) {
if(r>l||r+l>n) return;
if(r+l==n&&r==n/2&&l==n/2)
{
for(int i=0;i<n;i++)
{
System.out.print(c[i]);
}
count++;
System.out.println();
}
c[l+r]=‘(‘;
fun(n,r,l+1,c);
c[l+r]=‘)‘;
fun(n,r+1,l,c);
}
}