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:
"((()))", "(()())", "(())()", "()(())", "()()()"
solutions: dfs,解这道题的时候leetcode不停报错internal error...晚点再测试
class Solution {
public:
void generateResult(int left, int right, string result, vector<string> &res)
{
if(left == 0 && right == 0)
res.push_back(result);
if(left > 0)
generateResult(left-1, right, result + "(", res);
if(left < right)
generateResult(left, right-1, result + ")", res);
}
vector<string> generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> res();
if(n <= 0)
return res;
string result = "";
generateResult(n, n, result, res);
return res;
}
};

本文介绍了一个使用深度优先搜索(DFS)算法生成所有有效括号组合的方法。针对输入的整数n,该算法能够生成所有可能的有效括号组合。示例中展示了当n等于3时的有效括号组合。
106

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



