LeetCode22 Generate Parentheses 括号生成

题目:

Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, givenn= 3, a solution set is:

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

翻译:

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

思路:

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

名字叫做卡特兰数。

百度百科 viki

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

接下来说我的想法。这道题其实可以按照递归去做。每次把字符串压入到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 括号生成

相关文章:

你感兴趣的文章:

标签云: