LeetCode Ex22 Generate Parentheses

Generate Parentheses

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,n为括号的对数,返回所有括号的组合,且组合是合法的,即一个右括号总有一个左括号对应。

主要思想是回溯算法。n对括号,n个左括号为left,n个右括号right,当left != 0时,递归left-- path+“(”,当rigth!==&&right>left时,递归right-- path+“)”,直到left==0&&right==0时,将path添加到list中。
也就是说当左括号个数不为0时,可以添加左括号,右括号个数不为0并且大于左括号个数时,添加右括号。

回溯

    public List generateParenthesis(int n) {
        List list = new ArrayList();
        backtrack(list, "", 0, 0, n);
        return list;
    }

    public void backtrack(List list, String str, int open, int close, int max) {
        if (str.length() == max * 2) {
            list.add(str);
            return;
        }
        if (open < max)
            backtrack(list, str + "(", open + 1, close, max);
        if (close < open)
            backtrack(list, str + ")", open, close + 1, max);
    }

动态规划

    public List generateParenthesis2(int n) {
        List> lists = new ArrayList<>();
        lists.add(Collections.singletonList(""));
        for (int i = 1; i <= n; ++i) {
            final List list = new ArrayList<>();
            for (int j = 0; j < i; ++j) {
                for (final String first : lists.get(j)) {
                    for (final String second : lists.get(i - 1 - j)) {
                        list.add("(" + first + ")" + second);
                    }
                }
            }
            lists.add(list);
        }
        return lists.get(lists.size() - 1);
    }

你可能感兴趣的:(LeetCode Ex22 Generate Parentheses)