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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
思路:输入n,输出所有合法的n对括号的排列组合
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
addingpar(res, "", n, 0);
return res;
}
//n个左括号可以加,m个右括号需要加
void addingpar(vector<string> &v, string str, int n, int m) {
if (n == 0 && m == 0) {
v.push_back(str);
return;
}
if (m > 0) addingpar(v, str+")", n, m-1);
if (n > 0) addingpar(v, str+"(", n-1, m+1);//每加一个左括号,就需要多加一个右括号
}
};