##构造n对括号的全部有效组合
###思路
递归构造
- 左括号:只要还有左括号,则加入
- 右括号:只要右括号比左括号剩余的还多,则不构成非法,加入
###Code
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void GenerateParens(vector<vector<char>>& result,vector<char>& path,int left,int right,int count)
{
if(left < 0 || right < 0)
{
return;
}
if(left == 0 && right == 0)
{
result.push_back(path);
return;
}
else
{
if(left > 0)
{
path[count] = '(';
GenerateParens(result,path,left-1,right,count+1);
}
if(right > left)
{
path[count] = ')';
GenerateParens(result,path,left,right-1,count+1);
}
}
}
vector<vector<char>> GenerateParens(int n)
{
vector<char> path(n*2,'0');
vector<vector<char>> result;
GenerateParens(result,path,n,n,0);
return result;
}
int main()
{
vector<vector<char>> result = GenerateParens(3);
for(int i = 0 ; i < result.size() ; ++i)
{
for(int j = 0 ; j < result[i].size() ; ++j)
{
cout<<result[i][j];
}
cout<<endl;
}
system("pause");
return 0;
}