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:

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

C++:
01 void generateParenthesisHelp(vector<vector<string>>& A,
02                              int n)
03 {
04     vector<string> cur;
05     for(int i=0;i<n;i++)
06     {
07         string p=“(“;
08         for(int j=0;j<A[i].size();j++)
09         {
10             string q=p+A[i][j]+‘)’;
11             for(int k=0;k<A[ni1].size();k++)
12             {
13                 string tmp=q+A[ni1][k];
14                 cur.push_back(tmp);
15             }
16         }
17     }
18     A.push_back(cur);
19 }
20 class Solution {
21 public:
22     vector<string> generateParenthesis(int n) {
23         // Start typing your C/C++ solution below
24         // DO NOT write int main() function
25         vector<vector<string>> A;
26         vector<string> tmp;
27         tmp.push_back(“”);
28         A.push_back(tmp);
29         for(int i=1;i<=n;i++)
30         {
31             generateParenthesisHelp(A, i);
32         }
33         return A[n];
34     }
35 };
Advertisements
This entry was posted in Array and linked list, Dynamic programming, Recursive. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s