dfs · leetcode-22.产生括号组?

题面

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses 
给定int n,代表n组括号,编码生成所有有效的括号组合(即符合括号嵌套规则)

 样例

given n = 3, a solution set is: 
[ 
  "((()))", 
  "(()())", 
  "(())()", 
  "()(())", 
  "()()()" 
]

思路

dfs

源码

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> res;
 5         dfs("", 0, 0, res, n);
 6         return res;
 7     }
 8     //dfs深搜
 9     void dfs(string tmp, int l, int r, vector<string> &res, int n)
10     {
11         if(l == n && r == n)
12         {
13             res.push_back(tmp);
14             return ;
15         }
16         if(l < n)
17             dfs(tmp+"(", l+1, r, res, n);
18         if(l > r)
19             dfs(tmp+")", l, r+1, res, n);
20     }
21 };
posted @ 2019-05-16 11:58  yocichen  阅读(213)  评论(0编辑  收藏  举报