题目:
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组括号,符合括号的规则
思路:
这道题以前学数据结构的时候曾经做过,和出栈的个数有关系。
名字叫做卡特兰数。
附上一些大牛的关于卡特兰数的讲解。
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); }
时间: 2024-07-31 15:23:23