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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
思維大概就是用DFS方式,爬二元數,往左邊兒子是"(" ,往右邊兒子是")" 。
如果"(" 還沒達到 n,就先儘量往左兒子走。
如果"(" 數目比 ")" 少,也先儘量往左兒子走。
如果 "(" 數目和 ")" 相等且跟n相等,那麼就是其中一種可能
class Solution {
public:
vector<string> answer;
vector<string> generateParenthesis(int n) {
if(n<=0) {
return vector<string>();
}
string str;
DFS(0, 0, str, n);
return answer;
}
void DFS(int L, int R, string str, int n) {
if(L == n && R == n) {
answer.push_back(str);
} else {
if(L < n) {
DFS(L+1, R, str+"(", n);
}
if(R < L) {
DFS(L, R+1, str+")", n);
}
}
}
};