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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
簡要題解:
從左到右開始統計,無論何時左括號的數量一定都大於或等於右括號的數量。
可以從空狀態開始,逐步嘗試在右邊添加一個括號。配合使用遞歸+回溯的方法可找出所有合法的組合。
代碼:
class Solution {
public:
vector<string> generateParenthesis(int n) {
result.clear();
recurGenerate("", n, n);
return result;
}
private:
vector<string> result;
void recurGenerate(string s, int l, int r) {
if (0 == l && 0 == r) {
result.push_back(s);
return;
}
if (l > r)
return;
if (l > 0)
recurGenerate(s + "(", l - 1, r);
if (r > 0)
recurGenerate(s + ")", l, r - 1);
}
};