码迷,mamicode.com
首页 > 其他好文 > 详细

Generate Parentheses

时间:2014-10-21 12:26:59      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   java   for   sp   div   

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 class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list=new LinkedList<String>();
        if(n==0)
        {
            return list;
        }
        List<List<String>> lists=new ArrayList<List<String>>(n+1);
        lists.add(list);
        list=new LinkedList<String>();
        list.add("()");
        lists.add(list);
        for(int i=2;i<=n;i++)
        {
            list=new LinkedList<String>();
            for(String element:lists.get(i-1))
            {
                list.add("()"+element);
                list.add("("+element+")");
            }
            for(int j=2;j<i;j++)
            {
                for(String pLeft:lists.get(j-1))
                {
                    for(String pRight:lists.get(i-j))
                    {
                        list.add("("+pLeft+")"+pRight);
                    }
                }
            }
            lists.add(list);
        }
        return lists.get(n);
    }
}


Generate Parentheses

标签:style   blog   color   io   ar   java   for   sp   div   

原文地址:http://blog.csdn.net/jiewuyou/article/details/40340403

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!