首页 > 其他 > 详细

Generate Parentheses

时间:2015-11-28 21:27:45      阅读:341      评论: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:

"((()))", "(()())", "(())()", "()(())", "()()()"

 1 #include <vector>
 2 #include <string>
 3 using namespace std;
 4 class Solution {
 5 public:
 6     vector<string> generateParenthesis(int n) {
 7         vector<string> result;
 8         vector<bool> path;
 9         dfs(0,0,0,path,result,n);
10         return result;   
11     }
12 
13 private:
14     void dfs(int curr,int r,int l,vector<bool>& path,
15         vector<string>& result,int n){
16         if(curr == 2*n){
17             string s;
18             for(int i=0;i<2*n;i++){
19                 if(path[i]==true){
20                     s.push_back(();
21                 }else s.push_back());
22             }
23             result.push_back(s);
24             return;
25         }
26         
27         if(r==l){
28             path.push_back(true);
29             dfs(curr+1,r+1,l,path,result,n);
30             path.pop_back();
31         }else if(r>l && r<n){
32             path.push_back(true);
33             dfs(curr+1, r+1, l, path, result, n);
34             path.pop_back();
35             path.push_back(false);
36             dfs(curr+1, r, l+1, path, result, n);
37             path.pop_back();
38         }else{
39             path.push_back(false);
40             dfs(curr+1,r,l+1,path,result,n);
41             path.pop_back();
42         }
43         
44     }
45 };
46 
47 int main()
48 {
49     Solution s;
50     vector<string> result;
51     result = s.generateParenthesis(3);
52     return 0;
53 }

 

 

Generate Parentheses

原文:http://www.cnblogs.com/wxquare/p/5003432.html

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