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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
Test instructions: An integer n requirement is combined into a string consisting of n pairs of parentheses, which requires the output of all possible permutations.
Idea: Recursive deep search, notice two conditions, can insert ' (' The condition is must be the remaining number greater than 0, be able to insert ') ' The condition is that the number of the remaining is greater than 0 and the remaining ') ' number is greater than the remaining ' (' number, but be sure to construct a good DFS function parameters.
Class Solution {public
:
vector<string>ans;
vector<string> generateparenthesis (int n) {
Dfs ("", n,0);
return ans;
}
void Dfs (String s,int l,int r)
{
if (l==0&&r==0)
{
ans.push_back (s);
return;
}
if (l>0)
{
string s1=s+ ' (';
Dfs (s1,l-1,r+1);
}
if (r>0)
{
string s1=s+ ') ';
Dfs (s1,l,r-1);}}
;