首页 > 其他 > 详细

[leetcode-22-Generate Parentheses]

时间:2017-05-26 18:44:58      阅读:297      评论:0      收藏:0      [点我收藏+]

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.

void addParenthesis(vector<string>& res, string str, int open, int close,int n)
     {
         if (str.length() == n*2)
         {
             res.push_back(str);
             return;
         }
         if (open<n)addParenthesis(res, str + "(", open + 1, close, n);
         if (close < open)addParenthesis(res, str + ")", open, close + 1, n);         
     }
     vector<string> generateParenthesis(int n)
     {
         vector<string>res;
         addParenthesis(res, "", 0, 0, n);
         return res;
     }

参考:

https://discuss.leetcode.com/topic/4485/concise-recursive-c-solution

[leetcode-22-Generate Parentheses]

原文:http://www.cnblogs.com/hellowooorld/p/6909946.html

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