首页 > 其他 > 详细

dfs · leetcode-22.产生括号组

时间:2019-05-16 12:16:29      阅读:136      评论:0      收藏:0      [点我收藏+]

22.产生括号组


string dfs

题面

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. };
 

dfs · leetcode-22.产生括号组

原文:https://www.cnblogs.com/yocichen/p/10874799.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!