问题描述
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对括号,输出有n对括号的所有合理的结果。
合理的括号匹配指所有的左括号都有右括号对应。
使用递归,输入为result的引用,当前累加的string和左右括号的数目,有多少个左括号,就要用多少个右括号,当所有的左右括号都匹配完成了,则一个合理的括号匹配结果就产生了。
一开始只有左括号,则只能插入左括号,并可以插右括号了,n–,m++;有了左括号了就可以插入右括号了,相应的–就可以了
代码
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
addParentheses(result, "", n, 0);
return result;
}
void addParentheses(vector<string> &v, string str, int n, int m){
if (n == 0 && m == 0){
v.push_back(str);
return;
}
if (m > 0)
addParentheses(v, str + ")", n, m - 1);
if (n > 0)
addParentheses(v, str + "(", n - 1, m + 1);
}
};
时间复杂度:
O(n)
O
(
n
)
空间复杂度:
O(n)
O
(
n
)
反思
很巧妙,还没有完全理解这个递归的方式。