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:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路:递归:也就两种选择,要么左括号,要么右括号,分别记录个数;只要左括号的个数大于0的话,那么就可以填写左括号;右括号的话,那么要确保此时的序列,左括号的个数要大于右括号的个数。
class Solution {
public:
void print(int left, int right, string s, vector<string> &result) {
if (left == 0 && right == 0) {
result.push_back(s);
}
if (left > 0) {
print(left-1, right, s+'(', result);
}
if (right > 0 && left < right) {
print(left, right-1, s+')', result);
}
}
vector<string> generateParenthesis(int n) {
vector<string> result;
string tmp = "";
print(n, n, tmp, result);
return result;
}
};