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:

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

 

使用深度搜索,有n对括号,那么就有2n个位置,需要在0...2n-1的位置上放满(和),可以从0号位置上依次放(和),假如准备放i号位置,这是需要查看0....i-1的位置上(的数量和)的数量,

如果(的数量和)的数量相等,那么i号位置只能放(。

如果(的数量大于)的数量,那么i号位置可以放(或).

如果(的数量小于)的数量,那么说明在0...i-1位置的()形式有问题的

最后(无剩余,同时)也无剩余,那么此时0...2n-1上()的形式是正确的。

代码如下:

 

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         ans.clear();
 5         string str;
 6         dfs(str, n, n);
 7         return ans;
 8     }
 9     
10     void dfs(string& tstr, int leftnum, int rightnum) {
11         //leftnum为左括号的剩余数,rightnum为右括号的剩余数
12         //如果左括号的剩余数多,那说明之前放得()形式不正确
13         //始终需要保证前面左括号的数量大于等于右括号的数量,那么左括号的剩余数就要小于等于右括号的剩余数
14         if( leftnum > rightnum ) return ;   //间接保证左括号数==右括号数的情况下,优先放左括号
15         if( leftnum == 0 && rightnum == 0 ) {   //当左括号和右括号剩余数均为0的情况下,那么这是个符合要求的括号集
16             ans.push_back(tstr);
17             return ;
18         }
19         if( leftnum > 0 ) {     //左括号还有剩余
20             tstr.push_back('(');
21             dfs(tstr, leftnum-1, rightnum);
22             tstr.pop_back();
23         }
24         if( rightnum > 0 ) {    //右括号还有剩余
25             tstr.push_back(')');
26             dfs(tstr, leftnum, rightnum-1);
27             tstr.pop_back();
28         }
29     }
30     
31 private:
32     vector<string> ans;
33 };

 

posted on 2014-09-02 09:58  bug睡的略爽  阅读(392)  评论(0编辑  收藏  举报

导航