/*
22. Generate Parentheses My Submissions QuestionEditorial Solution
Total Accepted: 85070 Total Submissions: 231341 Difficulty: Medium
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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
Subscribe to see which companies asked this question
*/
/*
解题思路:
利用深度遍历dfs
能够往下走的条件就是左括号数 、右括号数有没达到n值得。在每一步过程中必须保证left>=right,否则返回
*/
class Solution {
public:
vector<string> generateParenthesis(int n) {
//此题用深度遍历即可
vector<string> res;
dfs(n,0,0,"",res);
return res;
}
void dfs(int n,int left,int right,string out,vector<string>&res){
if(left==n&& right==n){
res.push_back(out);
return ;
}
if(right>left || left>n )return ;
dfs(n,left+1,right,out+'(',res);
dfs(n,left,right+1,out+')',res);
}
};