Generate Parentheses
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Thinking
Reading from left to right, at any position, count of ')' can't be greater than count of '('.
My Code
class Solution {
public:
vector<string> strs;
vector<string> generateParenthesis(int n) {
helper("", n, n);
return strs;
}
void helper(string str, int left_cnt, int right_cnt)
{
if (left_cnt == 0 && right_cnt == 0)
{
strs.push_back(str);
return ;
}
if (left_cnt > 0)
helper(str + '(', left_cnt - 1, right_cnt);
if (right_cnt > left_cnt)
helper(str + ')', left_cnt, right_cnt - 1);
}
};
Runtime:
0 ms