给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
if (n == 0) {
ans.push_back("");
} else {
for (int c = 0; c < n; ++c)
for (string left: generateParenthesis(c))
for (string right: generateParenthesis(n-1-c))
ans.push_back("(" + left + ")" + right);
}
return ans;
}
};
本文介绍了一个使用递归方法生成有效括号组合的C++函数。当输入为整数n时,该函数会生成所有可能的有效括号组合。通过递归调用自身来构造合法的括号序列。
464

被折叠的 条评论
为什么被折叠?



