[Java]LeetCode22 Generate Parentheses

来源:互联网 发布:grub添加windows引导 编辑:程序博客网 时间:2024/06/09 12:58

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());        }    }


0 0
原创粉丝点击