首页 > 其他 > 详细

LeetCode22 Generate Parentheses 括号生成

时间:2015-05-05 14:27:21      阅读:122      评论: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:

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


翻译:

给你一个N ,生成N组括号,符合括号的规则


思路:

这道题以前学数据结构的时候曾经做过,和出栈的个数有关系。

名字叫做卡特兰数。

百度百科    viki


附上一些大牛的关于卡特兰数的讲解。

http://www.cnblogs.com/wuyuegb2312/p/3016878.html

接下来说我的想法。这道题其实可以按照递归去做。每次把字符串压入到List的结束条件是左括号和右括号剩余都为0。且在递归过程中,保持左括号的个数大于等于右括号即可。

代码:

    	public static List<String> generateParenthesis(int n) {
        List<String> ls = new ArrayList<String>();
        if(n <= 0)
        	return ls;
        Gen(n,n,"",ls);
        
        return ls;
		
    }
	public static void  Gen(int l,int r,String s,List<String>ls)
	{
		if(r < l)
			return ;
		if(l==0&&r == 0)
			ls.add(s);
		if(l > 0)
			Gen(l-1,r,s+'(',ls);
		if(r > 0)
			Gen(l,r-1,s+')',ls);
	}





LeetCode22 Generate Parentheses 括号生成

原文:http://blog.csdn.net/vvaaiinn/article/details/45501289

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