题目:
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> result;
string s = "";
vector<string> generateParenthesis(int n) {
generate(n, n, s);
return result;
}
void generate(int left_leave, int right_leave, string s) {
if(left_leave == 0 && right_leave == 0) {
result.push_back(s);
return;
}
if(left_leave == right_leave) {
generate(left_leave - 1, right_leave, s + "(");
}
if(left_leave < right_leave) {
if(left_leave != 0) {
generate(left_leave - 1, right_leave, s + "(");
}
generate(left_leave, right_leave - 1, s + ")");
}
}
};
思路:
递归,看代码应该很好理解,故不做赘述。