lintcode,生成括号

来源:互联网 发布:淘宝阿迪旗舰店是正品 编辑:程序博客网 时间:2024/05/17 01:49

给定 n 对括号,请写一个函数以将其生成新的括号组合,并返回所有组合结果。
样例
给定 n = 3, 可生成的组合如下:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

一刷没ac
解题思路:类似dp的思想,考虑n个括号是有n-1生成来的,相当于将所有n-1拆为两部分,再加入一个括号。也可以在n-1的基础上每个可能的位置都插入一个括号。

public class Solution {    /**     * @param n n pairs     * @return All combinations of well-formed parentheses     */    public ArrayList<String> generateParenthesis(int n) {        ArrayList<String> res = new ArrayList<String>();        if(n == 0) {            res.add("");            return res;        }        for(int i = 0; i < n; i++){            ArrayList<String> head = generateParenthesis(i);            ArrayList<String> tail = generateParenthesis(n-1-i);            for(String strhead : head){                for(String strtail : tail){                    res.add("("+strhead+")"+strtail);                }            }        }        return res;    }}
public class Solution {    public List<String> generateParenthesis(int n) {        List<String> res = new ArrayList<String>();        if(n < 1) return res;        if(n == 1){            res.add("()");            return res;        }        List<String> pre = generateParenthesis(n-1);        HashSet<String> set = new HashSet<String>();        for(int i = 0; i < pre.size(); i++){            String str = pre.get(i);            for(int j = 0; j <= str.length(); j++){                String first = str.substring(0, j);                String last = str.substring(j, str.length());                set.add(first+"()"+last);            }        }        for(String s : set){            res.add(s);        }        return res;    }}
0 0
原创粉丝点击