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: vector<string> generateParenthesis(int n) { vector<string> res; string out; DFS(n,0,0,out,res); return res; } void DFS(int n,int l,int r,string &out,vector<string> &res) { if(l==n&&r==n) { res.push_back(out); return; } else { if(l<n) { out.push_back(‘(‘); DFS(n,l+1,r,out,res); out.pop_back(); } if(l>r) { out.push_back(‘)‘); DFS(n,l,r+1,out,res); out.pop_back(); } } } };
Leetcode generate-parentheses(生成括号, DFS)
原文:https://www.cnblogs.com/zl1991/p/12783710.html