四对括号可以有多少种匹配排列方式

时间:2022-03-17 04:11:05

四对括号可以有多少种匹配排列方式?比如两对括号可以有两种:()()和(())

借鉴于前面的一篇博文,寻找满足条件的多个数

#include <iostream>
#include <list>
using namespace std;

#define N8
int sum = 0;
list<char> arrayList;

void arrayCount(int firstCount, int secondCount, int number)
{
if (firstCount < secondCount || number < 0 || firstCount > N / 2 || secondCount > N / 2)
{
return;
}

if (firstCount == N / 2 && secondCount == N / 2 && number == 0)
{
sum++;
for (list<char>::iterator it = arrayList.begin(); it != arrayList.end(); it++)
{
cout<<*it<<" ";
}
cout<<endl;
}

arrayList.push_back('(');
firstCount++;
arrayCount(firstCount, secondCount, number-1);
arrayList.pop_back();
firstCount--;
arrayList.push_back(')');
secondCount++;
arrayCount(firstCount, secondCount, number-1);
arrayList.pop_back();
secondCount--;//最后这两行不能忘记,否则会使得arrayList无故的变大
}

int main()
{
arrayCount(0, 0, N);
cout<<sum;
}