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) {
vector<string> vec;
add(vec, "", n, 0);
return vec;
}
void add(vector<string>& vec, string str, int n, int m) {
if (n == 0 && m == 0) {
vec.push_back(str);
}
if (m > 0) {
add(vec, str + ')', n, m - 1);
}
if (n > 0) {
add(vec, str + '(', n - 1, m + 1);
}
}
};