问题
https://leetcode.com/problems/generate-parentheses/
解法
dfs + 剪枝
class Solution {
public:
void search(vector<string>& res, char * s, int lNum, int depth, int n)
{
if (depth ==n)
{
if (lNum == 0)
res.push_back(string(s));
return;
}
// '('
s[depth] = '(';
if (lNum+1 <= (n-1-depth))
search(res, s, lNum+1, depth+1, n);
s[depth] = ')';
if (lNum-1 >= 0)
search(res, s, lNum-1, depth+1, n);
}
vector<string> generateParenthesis(int n) {
vector<string> ret;
if (n==0)
return ret;
char s[2*n+1];
s[2*n] = 0;
search(ret, s, 0, 0, 2*n);
return ret;
}
};
本文介绍了一种使用深度优先搜索(DFS)结合剪枝策略来解决括号生成问题的算法。该算法通过递归地在字符串中添加左括号和右括号,并在满足条件时将合法的括号组合加入结果集,最终返回所有可能的有效括号组合。
828

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



