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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Solution { public : vector<string> generateParenthesis( int n) { vector<string> res; dfs(res, "" ,n,0); return res; } void dfs(vector<string> &res, string str, int l, int r){ if (l == 0 && r ==0){ res.push_back(str); return ; } if (l > 0) dfs(res, str+ ‘(‘ , l - 1, r + 1); if (r > 0) dfs(res, str+ ‘)‘ , l, r - 1); } }; |
原文:http://www.cnblogs.com/zhxshseu/p/a44db0600fe2adbb31aa501a69be6cec.html