一、 问题描述
Leecode第二十二题,题目为:
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
问题理解为:
给定n对括号,编写一个函数来生成所有规范的括号组合。
例如,给定n = 3,解集为:
[
”((()))”,
”(()())”,
”(())()”,
“()(())”,
”()()()”
]
二、算法思路
1、
2、
三、实现代码
class Solution {
public:
vector<string> res;
vector<string> generateParenthesis(int n) {
fun(0, 0, "", n);
return res;
}
void fun(int left, int right, string s, int n) {
if(right == n) {
res.push_back(s);
}
else
{
if(left < n)
{
fun(left + 1, right, s + "(", n);
}
if(right < left)
{
fun(left, right + 1, s + ")", n);
}
}
}
};