[LeetCode]22. Generate Parentheses

来源:互联网 发布:youtube电视软件下载 编辑:程序博客网 时间:2024/04/30 16:51

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 = k 时,每个排列中有 2k 个半括号 ,当增加一对新的括号时,有2k + 1 个可以插入的位置,即每两个半括号之间都可以插曲一对新括号(包括边界)

 针对 n = k 时的全部组合做这种插入,去掉重复结果,就得到 n = k + 1 时的结果

代码如下:

    public List<String> generateParenthesis(int n) {        List<List<String>> res = new ArrayList<List<String>>();        String temp = "()";        List<String> restemp1 = new ArrayList<String>();        List<String> comp = new ArrayList<String>();        restemp1.add(temp);        res.add(restemp1);        for (int i = 1; i < n; i++) {            List<String> restemp = new ArrayList<String>();            HashSet<String> h = new HashSet<String>();            comp = res.get(i-1);            for(int j = 0; j < comp.size(); j++) {                int len = comp.get(j).length();                for(int k = 0; k < len; k++) {                    temp = comp.get(j).substring(0,k) + "()" + comp.get(j).substring(k,len);                    if (h.contains(temp) == false) {                    h.add(temp);                    restemp.add(temp);                    }                }            }            res.add(restemp);        }        return res.get(n-1);    }




0 0
原创粉丝点击