LeetCode 22 -Generate Parentheses ( JAVA )

来源:互联网 发布:四维星软件破解版 编辑:程序博客网 时间:2024/05/22 17:37

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:

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

public class Solution {    public List<String> generateParenthesis(int n) {    ArrayList<String> al = new ArrayList<String>();        String s = "";        fun(al,s,n,n);        return al;    }    public void fun(ArrayList<String> al,String s , int l ,int r){        if(l == 0 && r == 0){            al.add(s);        }        if(l > 0 ){            fun(al , s + "(" , l-1 , r);        }        if(l < r && r > 0){            fun(al , s + ")" , l , r-1);        }    }}



总结:看了题目只知道是递归解决,想了半天没想出来,查到的结果是卡特兰数,题目的解法过于繁琐,参考了一下现在这个代码,超级简洁,超级清洗,建议看一下,他的一些思想,下面就是参考链接;

参考文献:http://www.makuiyu.cn/2015/01/LeetCode_22.%20Generate%20Parentheses/


0 0
原创粉丝点击