给定 n,表示有 n 对括号, 请写一个函数以将其生成所有的括号组合,并返回组合结果。
样例
样例 1:
输入: 3
输出: ["((()))", "(()())", "(())()", "()(())", "()()()"]
样例 2:
输入: 2
输出: ["()()", "(())"]
class Solution {
public:
/**
* @param n: n pairs
* @return: All combinations of well-formed parentheses
*/
vector<string> generateParenthesis(int n) {
if (n == 0) return {""}; // 基本情况
vector<string> ans;
for (int i = 0; i < n; i++)
{
for (string left : generateParenthesis(i)) // 挑选 s
{
for (string right : generateParenthesis(n - i - 1)) // 挑选 t
{
ans.push_back("(" + left + ")" + right); // 构造
}
}
}
return ans;
// write your code here
}
};