[Java]LeetCode22 Generate Parentheses

本文介绍了一种使用递归方法生成所有正确闭合的括号组合的算法。针对给定的括号对数n,该算法能够输出所有可能的正确闭合括号序列。

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:

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

题意:给出括号的对数,输出格式正确的括号排列。就是正常闭合的括号。

解题思路:用递归的方法。

public List<String> generateParenthesis(int n) {
     List<String> result=new ArrayList<String>();
     if(n==0)return result;
     StringBuffer buffer=new StringBuffer();
     addParenthesis(buffer,result,n,n);
     return result;
    }
    void addParenthesis(StringBuffer buffer,List<String> result,int leftNum,int rightNum)
    {
        if(leftNum>rightNum)return;//如果左括号的个数大于右括号的,返回。
        if(leftNum==0&&rightNum==0)
        {
            result.add(buffer.toString());
        }
        if(leftNum>0)//加左括号
        {
            buffer.append('(');
            addParenthesis(buffer,result,leftNum-1,rightNum);
            buffer.delete(buffer.length()-1, buffer.length());

        }
        if(rightNum>0)//加右括号
        {
            buffer.append(')');
            addParenthesis(buffer,result,leftNum,rightNum-1);
            buffer.delete(buffer.length()-1, buffer.length());

        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值