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

Generate Parentheses***

时间:2017-11-21 22:16:37      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:array   logs   ring   write   amp   new   return   rate   blog   

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> res = new ArrayList<String>();
        helper(n, n, "", res);
        return res;
    }
    void helper(int left, int right, String out, List<String> res) {
        if (left < 0 || right < 0 || left > right) return;
        if (left == 0 && right == 0) {
            res.add(out);
            return;
        }
        helper(left - 1, right, out + "(", res);
        helper(left, right - 1, out + ")", res);
    }
    

Generate Parentheses***

标签:array   logs   ring   write   amp   new   return   rate   blog   

原文地址:http://www.cnblogs.com/bingo2-here/p/7875259.html

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