题目:
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;
vector<string> generateParenthesis(int n) {
string tmp;
generate(tmp, n, n);
return result;
}
void generate(string &res, int m, int n){
if(m == 0 && n == 0){
result.push_back(res);
return;
}
if(m > 0){
res.push_back('(');
generate(res, m - 1, n);
res.pop_back();
}
if(n > 0 && m < n){
res.push_back(')');
generate(res, m, n - 1);
res.pop_back();
}
}
};

本文提供了一种使用递归方法生成所有长度为n对的合法括号组合的方法,并通过实例展示了生成过程。
275

被折叠的 条评论
为什么被折叠?



