[leetcode][22] Generate Parentheses

22. 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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

解析

括号匹配,输入括号总对数,返回所有可能括号排序的结果。需要注意的是一定先有左,才有右括号,构建过程中的任一时刻都是左括号数大于等于右括号数。

参考答案

自己写的:

class Solution {
    public List<String> generateParenthesis(int n) {
        if (n == 0) {
            return new ArrayList<>();
        }
        LinkedList<Parenthesis> list = new LinkedList<>();
        String left = "(";
        String right = ")";
        Parenthesis p = new Parenthesis();
        p.value = "(";
        p.left = 1;
        p.right = 0;
        list.add(p);
        while (list.peek().right != n ) {
            Parenthesis p1 = list.remove();
            if (p1.left < n) {
                Parenthesis p2 = p1.createNewInstance();
                p2.value += left;
                p2.left = p2.left + 1;
                list.addLast(p2);
            }
            if (p1.left - p1.right > 0) {
                Parenthesis p3 = p1.createNewInstance();
                p3.value += right;
                p3.right += 1;
                list.addLast(p3);
            }
        }
        List<String> res = new ArrayList<>();
        for (Parenthesis entity : list) {
            res.add(entity.value);
        }
        
        return res;
    }

    class Parenthesis {
        public String value;
        public int left;
        public int right;

        public Parenthesis createNewInstance() {
            Parenthesis p1 = new Parenthesis();
            p1.value = this.value;
            p1.left = this.left;
            p1.right = this.right;
            return p1;
        }
    }
}

我想的是每次循环都要判断左括号和右括号的数量,所以新建了一个数据结构来保存,实际上用递归就不用了,所以自己写的比较麻烦。还有就是捡了一个队列来做循环,每次循环都要用上次的数据。

别人写的:

class Solution {
     public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String>();
        backtrack(list, "", 0, 0, n);
        return list;
    }
    
    public void backtrack(List<String> 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);
    }
}

这样就很简单了,每个递归元都有所有信息,左括号的数量和右括号的数量。效率也高了。

猜你喜欢

转载自www.cnblogs.com/ekoeko/p/9636972.html