Generate Parentheses

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 }

 

 

posted @ 2015-11-28 20:57  wxquare  阅读(153)  评论(0编辑  收藏  举报