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

转载于:https://www.cnblogs.com/springfor/p/3886559.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值