题目描述:
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: "((()))", "(()())", "(())()", "()(())", "()()()"
这题没做出来,惭愧。
solution:
void dfs(vector&result,string str,int left,int right){ if(left > right) return; if (left == 0 && right == 0) { result.push_back(str); return; } if(left > 0) dfs(result, str+"(", left-1, right); if(right > 0) dfs(result, str+")", left, right-1);}vector generateParenthesis(int n) { vector res; if(n < 1) return res; dfs(res, "", n, n); return res;}
原文链接: