码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Generate Parentheses

时间:2014-12-29 22:47:51      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

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:

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

 
 
用递归生成所有的括号组合,并且在递归过程中不断剪枝
剪枝的条件:
 leftNum>n||rightNum>n||rightNum>leftNum)
1.左、右括号数目大于了n
2.右括号数目大于了左括号数目
 
 
 1 class Solution {
 2 
 3 public:
 4 
 5     vector<string> generateParenthesis(int n) {
 6 
 7        
 8 
 9         vector<string> result;
10 
11         generate(result,"",0,n,0,0);
12 
13         return result;
14 
15        
16 
17     }
18 
19    
20 
21     void generate(vector<string> &result,string tmp,int index,int &n,int leftNum,int rightNum)
22 
23     {
24 
25         if(leftNum>n||rightNum>n||rightNum>leftNum)
26 
27         {
28 
29             return;
30 
31         }
32 
33         if(index==2*n)
34 
35         {
36 
37             result.push_back(tmp);
38 
39             return;
40 
41         }
42 
43        
44 
45         generate(result,tmp+"(",index+1,n,leftNum+1,rightNum);
46 
47         generate(result,tmp+")",index+1,n,leftNum,rightNum+1);
48 
49     }
50 
51 };

 

【leetcode】Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4192433.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!