题目描述
给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
"((()))", "(()())", "(())()", "()(())", "()()()"
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路:与按键盘给数字生成字母的思路一致,用dfs,注意判断,l==n&&r==n的时候才push,l<n的时候可以加左括号,r<l的时候可以加右括号
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(); } } } };