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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
題目鏈接:https://leetcode-cn.com/problems/generate-parentheses/
思路
就是一個遞歸遍歷每種情況的邏輯實現。
class Solution {
public:
vector<string> res;
vector<string> generateParenthesis(int n) {
if(n<=0) return res;
string s = "";
getstr(n,0,"");
return res;
}
void getstr(int n, int pre, string s){
if(n<=0 && pre<=0){
res.push_back(s);
return;
}
if(n>0){
getstr(n-1, pre+1, s+"(");
}
if(pre>0){
getstr(n, pre-1, s+")");
}
return;
}
};