[Leetcode 49] 22 Generate Parentheses

Problem:

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:

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

 

Analysis:

Also a backtracking problem. Each time either put a '(' or ')' into the current stack.

There's a optimization we can do, a well-formed parentheses must have the same number of '(' and ')', either one exceeds half of the n*2, it won't become a valid solution. So we can prune it as early as possible.

 

Code:

 1 class Solution {
 2 public:
 3     vector<string> res;
 4     int total;
 5     
 6     vector<string> generateParenthesis(int n) {
 7         // Start typing your C/C++ solution below
 8         // DO NOT write int main() function
 9         //res.clear();
10         total = n*2;
11         res.clear();
12         bc("(", 1, 0);
13         
14         return res;
15     }
16     
17     void bc(string path, int left, int right) {
18         if (left > total/2 || right > total/2)
19             return ;
20         
21         if (path.size()==total && valid(path)) {
22             res.push_back(path);
23             return ;
24         }
25         
26         bc(path+")", left, right+1);
27         bc(path+"(", left+1, right);
28         return ;
29     }
30     
31     bool valid(string s) {
32         int cnt = 1;
33         for (int i=1; i<s.size(); i++) {
34             if (s[i] == '(') cnt++;
35             if (s[i] == ')') cnt--;
36             
37             if (cnt < 0) return false;
38         }
39         
40         return true;
41     }
42 };
View Code

 

posted on 2013-05-25 14:33  freeneng  阅读(199)  评论(0编辑  收藏  举报

导航