Generate Parentheses(生成括号)

问题

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Have you met this question in a real interview? Yes
Example
Given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

分析

利用递归,记录下当前的字符串组成。每次必须是左括号先出现。我们可以用两个数来记录左括号和右括号还剩余的个数(当然正向记录也没有问题)。当左括号比右括号多时,可以加右括号,左括号可以随时加。当他们都为n,或者说剩余为0时满足条件加入集合即可。

代码

public class Solution {
    /**
     * @param n n pairs
     * @return All combinations of well-formed parentheses
     */
    public ArrayList generateParenthesis(int n) {
        // Write your code here
        ArrayList al=new ArrayList();
        tree(al,"",n,n);
        return al;
    }
    private void tree(ArrayList al,String temp,int left,int right){
        if(left==right&&right==0){
            al.add(temp);
            return;
        }
        if(left>0){
            tree(al,temp+"(",left-1,right);
        }
        if(right>0&&left

你可能感兴趣的:(Generate Parentheses(生成括号))