LeetCode: 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-1的情况,然后在n-1中的每个string的前面,后面加上()以及用()扩住整个string。可是后来意识到这样会少考虑在中间增加括号的情况。比如:n=4,(())(()),用上面的方法没法根据n=3得到。后来想n=4,用两个n=2产生?这种方法估计肯定不合适。

 

后来看到的方法也是用递归。但是是根据左右括号的数量进行递归。假设我现在有一个string s。我可以根据左右括号的数量,决定s的后一个是什么。

如果剩余的左括号的数量大于0,那么我就可以在下一个位置放一个(。

如果剩余的右括号的数量大于左括号(s中右括号数量少于左括号才可以放右括号),那么我可以在下一个位置放一个)。

public static ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> a = new ArrayList<String>();
        generate(n, n, "", a);
        return a;
        
    }
    public static void generate(int left, int right, String s, ArrayList<String> result) {
        if (left == 0 && right == 0) {
            result.add(s);
        }
        
        if (left > 0) {
            generate(left-1, right, s + "(", result);
        }
        
        if (right > left) {
            generate(left, right-1, s + ")", result);
        }
    }

 

 

posted on 2014-01-13 10:10  longhorn  阅读(186)  评论(0编辑  收藏  举报

导航