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:
"((()))", "(()())", "(())()", "()(())",
"()()()"
像這種類似的題目,通過回溯法來構造是比較好的了。回溯的依據是當前字符是添加左括號,還是添加右括號;爲了能夠正確的添加左右括號,設置curLeft,curRight來分別記錄此時的左、右括號數量,同時要滿足curLeft >= curRight,添加右括號的時候,要注意是否滿足這個條件,結束的條件,應該是不滿足這個條件,或者curRight == n構造一個完畢。
class Solution {
public:
//回溯法
void generateP(int n, int curLeft, int curRight, string curStr, vector<string> &ans)
{
if(curLeft < curRight)
return;
if(curRight == n)
{
ans.push_back(curStr);
return;
}
//添加左邊括號
if(curLeft < n)
{
curStr.push_back('(');
generateP(n, curLeft + 1, curRight, curStr, ans);
curStr.pop_back();
}
//添加右邊括號
if(curRight < n && curRight < curLeft)
{
curStr.push_back(')');
generateP(n, curLeft, curRight + 1, curStr, ans);
curStr.pop_back();
}
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
if(n > 0)
{
string curStr = "";
generateP(n, 0, 0, curStr, ans);
}
return ans;
}
};