首页 > 其他 > 详细

[Leetcode] Generate Parentheses

时间:2014-11-13 06:57:45      阅读:278      评论:0      收藏:0      [点我收藏+]

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:

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

 

Solution:

 1 public class Solution {
 2     public List<String> generateParenthesis(int n) {
 3         List<String> result=new ArrayList<String>(); 
 4         dfs(n,n,result,"");  
 5         return result;
 6     }
 7 
 8     private void dfs(int left, int right, List<String> result, String temp) {
 9         // TODO Auto-generated method stub
10         if(right<0||left<0)
11             return;
12         if(right==0&&left==0)
13             result.add(temp);
14         if(left>0)
15             dfs(left-1, right, result, temp+"(");
16         if(right>left)
17             dfs(left, right-1, result, temp+")");
18     }
19 }

 

[Leetcode] Generate Parentheses

原文:http://www.cnblogs.com/Phoebe815/p/4093977.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!