22. Generate Parentheses (recursion algorithm)
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
AC code:
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> v; string str = ""; helper(v, str, 0, 0, n); return v; } void helper(vector<string>& v, string str, int left, int right, int n) { if (right == n) { v.push_back(str); return; } if (left < n) { helper(v, str+'(', left+1, right, n); } if (right < left) { helper(v, str+')', left, right+1, n); } } };
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Generate Parentheses.
永远渴望,大智若愚(stay hungry, stay foolish)