这题看的第一眼,这不就是Catalan Number么 - - 这不就是递归么。这是我之前学Catalan Number的教材的部分摘录,看完就知道怎么写啦。
Catalan numbers:
Set P of balanced parentheses strings are recursively defined as
• λ ∈ P (λ is empty string)
• If α, β ∈ P, then (α) β ∈ P
Every nonempty balanced paren string can be obtained via Rule 2 from a unique α, β pair.
Cn : number of balanced parentheses strings with exactly n pairs of parenthesesC0 = 1 empty string
Cn+1? Every string with n + 1 pairs of parentheses can be obtained in a unique way via rule 2.
One paren pair comes explicitly from the rule.k pairs from α, n−k pairs from β
Cn+1 = sigma Ck · Cn−k n≥0 // CSDN的编辑器用不惯,直接写sigma,就是二项式求和嘛 T^T 想用$$写数学公式都显示不了?
C0 =1
C1 = C02 =1
C2 = C0C1 + C1C0 = 2
C3 = ··· = 5
1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640, 343059613650, 1289904147324, 4861946401452, 18367353072152, 69533550916004, 263747951750360, 1002242216651368
然后哼哧哼哧马上写好了,一次通过,可是妈蛋啊,只打败了 28% 的人- -
等我什么时候有空了再去看看别人很快的代码吧~
题目:
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
先贴上我的只打败了28%的代码- - ,只有8个测试用例,废话要是有40个,岂不算到下一次宇宙大爆炸。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if(n < 0)
return res;
if (n == 0){ // #0 = 1
res.push_back("");
return res;
}
if( n == 1){ // #1 = 1
res.push_back("()");
return res;
}
res = iter(n);
return res;
}
vector<string> iter(int N){
vector<string> res;
if(N == 0){
res.push_back("");
return res; //递归出口
}
if(N == 1){
res.push_back("()");
return res; //递归出口
}
for(int k = 0; k <= (N-1); k++){
string tempStr;
vector<string> temp1 = iter(k); //递归
vector<string> temp2 = iter(N-1-k); //递归
for(int i = 0; i < temp1.size(); i++){
for(int j = 0; j < temp2.size(); j++){
tempStr = "(" + temp1[i] + ")" + temp2[j];
res.push_back(tempStr);
}
}
}
return res;
}
};