Description
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example
Given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
Analyse
题意是要求你生成以n对括号组成的所有的正确形式的括号。
分析:既然是生成所有的可能,那么我们首先考虑的当然是遍历所有的可能,然后,我们就很容易会想到dfs去。我们可以设计一个这样的一个递归关系。
f(m,n)为有m个左括号和n个右括号需要添加,若当前添加的是左括号,那么f(m-1,n+1),因为要保证生成的东西的正确性,有左括号必须就得有右括号,所以n需要加一,若当前添加的是右括号,那么f(m,n-1)。直到m == 0 && n == 0,就得到了一个答案了。很明显,这样是可以生成所有的括号的组合的,但问题是,这样是否就能保证生成的组合都是正确的呢?由于我们这道题只有小括号,也就是说所有的括号等级都是一样的,我们只需要保证,左括号和右括号的数量相同,且左括号出现在右括号之前就行了,所以这种生成方法是可以的。
Code
class Solution {
public:
void resParenthesis(vector<string> &ans, string temp, int left, int right) {
if (left == 0 && right == 0) {
ans.push_back(temp);
} else {
if (left > 0) resParenthesis(ans, temp + "(", left - 1, right + 1);
if (right > 0) resParenthesis(ans, temp + ")", left, right - 1);
}
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
resParenthesis(ans, "", n, 0);
return ans;
}
};