22. Generate Parentheses

22. 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 /**
 2  * @param {number} n
 3  * @return {string[]}
 4  */
 5 var generateParenthesis = function(n) {
 6     
 7      var res = [];
 8     
 9     
10     // n == 0
11      if(n == 0){
12          return res;
13      }
14     
15     //n == 1;
16      if(n == 1){
17          
18          res.push("()");
19          return res;
20      }
21     
22     
23     
24     
25     //首先你会发现开头一定是"(",结尾一定是")";
26     
27     //还有一个明显的规律是 一定先有 "(" 再有")",也就是说,在没有到最后一个")"之前,"("的数目比右括号多
28     
29   
30 
31             
32     function innergenerateParenthesis(str,l,r,n){
33       
34          if(str.length == n*2){
35              
36              res.push(str);
37              return;
38          }
39         
40          if(l < n){
41              
42          
43              innergenerateParenthesis(str+"(",l+1,r,n);
44              
45          }
46         
47          if(r < l){
48              
49              
50              innergenerateParenthesis(str+")",l,r+1,n);
51              
52          } 
53         
54     }
55     
56     
57     innergenerateParenthesis("",0,0,n);
58     
59     
60     return res;
61      
62 };

 

posted @ 2017-10-14 16:39  hdu胡恩超  阅读(129)  评论(0编辑  收藏  举报