leetcode 22. Generate Parentheses

来源:互联网 发布:竹笛模拟软件 编辑:程序博客网 时间:2024/06/02 21:14

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个括号,找出所有的符合括号匹配的组合.

public class A22GenerateParentheses {public List<String> generateParenthesis(int n) {List<String> list = new ArrayList<String>();generate(list, "", n, n);return list;    }public void generate(List<String> list, String str, int lnum, int rnum) {if(lnum == 0 && rnum == 0) {list.add(str);}if(lnum > 0) {generate(list, str + "(", lnum - 1, rnum);}if(rnum > 0 && lnum < rnum) {generate(list, str + ")", lnum, rnum - 1);}}}
这道题是卡特兰数的应用.

卡塔兰数的一般项公式为Cn = C(2n, n)/(n + 1){\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!n!}}}

前20项为:1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190



0 0
原创粉丝点击