Generate Parentheses leetcode java


題目

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:

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

 

題解

 這道題跟unique binary tree ii是類似的。如果是只求個數的話是類似unique binary tree,用到了卡特蘭數。

這里也是用到了類似的模型。

 

不過這道題按照DFS那種遞歸想法解決還是比較容易想到的。

給定的n為括號對,所以就是有n個左括號和n個右括號的組合。

按順序嘗試知道左右括號都嘗試完了就可以算作一個解。

注意,左括號的數不能大於右括號,要不然那就意味着先嘗試了右括號而沒有左括號,類似“)(” 這種解是不合法的。

 

代碼如下:

 1      public ArrayList<String> generateParenthesis( int n) {  
 2         ArrayList<String> res =  new ArrayList<String>();
 3         String item =  new String();
 4         
 5          if (n<=0)
 6              return res;  
 7             
 8         dfs(res,item,n,n);  
 9          return res;  
10     }  
11       
12      public  void dfs(ArrayList<String> res, String item,  int left,  int right){ 
13          if(left > right) // deal wiith ")("
14               return;
15             
16          if (left == 0 && right == 0){  
17             res.add( new String(item));  
18              return;  
19         }
20         
21          if (left>0) 
22             dfs(res,item+'(',left-1,right);  
23          if (right>0) 
24             dfs(res,item+')',left,right-1);  
25     } 

Reference:

http://blog.csdn.net/linhuanmars/article/details/19873463

http://blog.csdn.net/u011095253/article/details/9158429


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM