标签:dfs leetcode 面试题 algorithm 二叉树
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
void dfs(vector<string> &re, string& cur_re, int unmatched_lefts, int added_lefts, int n)
{
if(unmatched_lefts == 0 && added_lefts == n)
{
re.push_back(cur_re);
}
if(unmatched_lefts > 0){//insert ')' is ok
cur_re.append(1, ')');
dfs(re, cur_re, unmatched_lefts - 1, added_lefts, n);
}
if(cur_re.size() > 0 && added_lefts < n)//can add another '('
{
cur_re.append(1,'(');
dfs(re, cur_re, unmatched_lefts + 1, added_lefts + 1, n);
}
cur_re.pop_back();
}
vector<string> generateParenthesis(int n) {
vector<string> re;
if(n <= 0)
return re;
string one_solve;
one_solve.append(1, '(');
dfs(re, one_solve, 1, 1, n);
return re;
}【leetcode】Generate Parentheses,布布扣,bubuko.com
【leetcode】Generate Parentheses
标签:dfs leetcode 面试题 algorithm 二叉树
原文地址:http://blog.csdn.net/shiquxinkong/article/details/27666691