题46
N对括号可以有多少种匹配排列方式?比如两对括号可以有两种:()()和(())
主要的思想还是递归!
#include "stdafx.h"
#include<iostream>
//#include<cassert>
#include <vector>
using namespace std ;
void Print(vector<char> v)
{
for (vector<char>::iterator beg=v.begin();beg!=v.end();++beg)
cout<<*beg<<" ";
cout<<endl;
}
void MatchNums(int nSize,int nLen,vector<char> &v)
{
int nLeftBrackets=0;
int nRightBrackets=0;
for (vector<char>::iterator beg=v.begin();beg!=v.end();++beg)
{
if(*beg=='(')
nLeftBrackets++;
else
nRightBrackets++;
if(nRightBrackets>nLeftBrackets)
return;
if(nLeftBrackets+nRightBrackets==nSize&&nLeftBrackets==nRightBrackets)
Print(v);
}
if (nLen>0)
{
v.push_back('(');
MatchNums(nSize,nLen-1,v);
v.pop_back();
v.push_back(')');
MatchNums(nSize,nLen-1,v);
v.pop_back();
}
}
int main()
{
vector <char> v;
int n=6;
MatchNums(n,n,v);
return 0;
}