括号。设计一种算法,打印n对括号的所有合法的(例如,开闭一一对应)组合。
说明:解集不能包含重复的子集。
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
法一:回溯法:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
string oneAns(n * 2, '\0');
generate(ans, 0, 0, oneAns, n);
return ans;
}
private:
void generate(vector<string> &ans, int leftNum, int rightNum, string &oneAns, int n)
{
if (rightNum == n)
{
ans.push_back(oneAns);
return;
}
int curIndex = leftNum + rightNum;
if (leftNum < n)
{
oneAns[curIndex] = '(';
generate(ans, leftNum + 1, rightNum, oneAns, n);
}
if (leftNum > rightNum)
{
oneAns[curIndex] = ')';
generate(ans, leftNum, rightNum + 1, oneAns, n);
}
}
};
法二:我们可以把n个括号组成的结果看成(a)b,其中a和b分别是合法的括号,因此我们只需要遍历所有长度的a和b即可:
class Solution {
public:
vector<string> generateParenthesis(int n) {
temp.resize(n + 1);
temp[0] = shared_ptr<vector<string>>(new vector<string>({""}));
return *generate(n);
}
private:
shared_ptr<vector<string>> generate(int length)
{
if (length == 0 || temp[length] != nullptr)
{
return temp[length];
}
temp[length] = shared_ptr<vector<string>>(new vector<string>());
for (int i = 1; i <= length; ++i)
{
shared_ptr<vector<string>> lv = generate(i - 1);
shared_ptr<vector<string>> rv = generate(length - i);
for (string &ls : *lv)
{
for (string &rs : *rv)
{
temp[length]->push_back("(" + ls + ")" + rs);
}
}
}
return temp[length];
}
vector<shared_ptr<vector<string>>> temp;
};
复杂度同法一。