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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
1 - 可以将此问题看作深度为n的dfs
2 - 定义一个递归函数dfs()。
- 其中well用于指示括号的顺序是否合法,增加左括号则well++,增加右括号则well–。若well<0则函数直接返回。当括号数量达到n*2时,well等于0则说明此括号组合的顺序合法。
- count用于记录深度,当count等于n*2时,则搜索停止。
- n为题目给定的深度。
- path为搜索路径,也即为括号的组合。
- result存储结果。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
dfs(0,0,n*2,"",result);
return result;
}
private:
void dfs(int well,int count,int n,string path,vector<string> &result){
//括号组合不合法
if(well<0) return;
//搜索达到指定深度
if(count==n){
//括号组合合法
if(well==0) result.push_back(path);
return;
}
//未达到指定深度,继续搜索
dfs(well+1,count+1,n,path+'(',result);
dfs(well-1,count+1,n,path+')',result);
}
};