leetcdoe22
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
第一想法是递归,可是自己写的递归错了,无奈去看别人的写法了,,,,,虽然看懂了,但是我自己并不能说的清楚,理解递归的最好的方法还是自己带个小点的数字进去自己实地的演练几次就会很轻松的了解。
class Solution { public: void g(vector<string>& vs, string & s, int left, int right, int n) { if (left == n && right == n) { vs.push_back(s); } if (left < n) { s.push_back('('); g(vs, s, left+1, right, n); s.pop_back(); } if (right < left) { s.push_back(')'); g(vs, s, left, right+1, n); s.pop_back(); } } vector<string> generateParenthesis(int n) { string s; vector<string> vs; g(vs, s, 0, 0, n); return vs; } };