Problem:
Description
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路
直接递归
Code
class Solution {
public:
std::vector<string> result;
vector<string> generateParenthesis(int n) {
generateCombinations(n-1, n, "(");
return result;
}
void generateCombinations(int n, int m, string s) {
if (n == 0 && m == 0) {
result.push_back(s);
return;
}
if (n > 0)
generateCombinations(n-1, m, s+"(");
if (n < m)
generateCombinations(n, m-1, s+")");
}
};