Leet Code上的题
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
代码如下:
void printPar(int L, int R, vector<string>& result, char* str, int idx)
{
if (L < 0 || R < L) return;
if (L == 0 && R == 0)
{
str[idx] = '\0';
result.push_back(string(str));
}
else
{
if (L > 0)
{
str[idx] = '(';
printPar(L-1, R, result, str, idx+1);
}
if (R > L)
{
str[idx] = ')';
printPar(L, R-1, result, str, idx+1);
}
}
}
vector<string> generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> result;
char* str = new char[2*n+1];
printPar(n, n, result, str, 0);
delete []str;
return result;
}