Description
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Solution
n对括号串可以拆分成几种情况:
(
+n-1对括号串
+)
i对括号串
+n-i对括号串
n-i对括号串
+i对括号串
所以用递归
注意:
- 调用层数越少越好,i<=n/2
- 去掉重复元素
class Solution {
public:
vector<string> combine(vector<string> p1, vector<string> p2)
{
vector<string> res;
int l1(p1.size()),l2(p2.size());
if(l1==l2)
{
for(int i = 0 ; i < l1 ; ++i)
for (int j = 0 ; j <l2 ;++j)
res.push_back(p1[i]+p2[j]);
}
else
{
for(int i = 0 ; i < l1 ; ++i)
for (int j = 0 ; j <l2 ;++j)
{
res.push_back(p1[i]+p2[j]);
res.push_back(p2[j]+p1[i]);
}
}
return res;
}
vector<string> generateParenthesis(int n) {
int curLen;
vector<string> res;
if (n == 0) return res;
if (n == 1) {
res.push_back("()");
return res;
}
vector<string> curRes,curRes2;
for(int i = 1 ; i <= n/2 ; ++i)
{
curRes = generateParenthesis(i);
if(n-i == i) curRes2=curRes;
else curRes2 = generateParenthesis(n-i);
curRes = combine(curRes,curRes2);
res.insert(res.end(),curRes.begin(),curRes.end());
if(i==1)
{
curLen = curRes2.size();
for(int j = 0 ; j < curLen ; ++j) res.push_back("("+curRes2[j]+")");
}
}
sort(res.begin(),res.end());
res.erase(unique(res.begin(), res.end()), res.end());
return res;
}
};
结果:
Runtime: 8 ms, faster than 98.05% of C++ online submissions for Generate Parentheses.
Memory Usage: 12 MB, less than 87.44% of C++ online submissions for Generate Parentheses.
20190402
tbc