首页 > 其他 > 详细

LeetCode - Generate Parentheses

时间:2015-12-20 12:58:28      阅读:217      评论:0      收藏:0      [点我收藏+]

题目:

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:

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

思路:

对于n个"("和n个")",在递归时保证"("的个数大于")"的个数

package recursion;

import java.util.ArrayList;
import java.util.List;

public class GenerateParentheses {

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        generate(res, n, n, "");
        return res;
    }
    
    private void generate(List<String> res, int left, int right, String s) {
        if (left == 0 && right == 0) {
            res.add(s);
            return;
        }
        
        if (left > 0) 
            generate(res, left - 1, right, s + "(");
        
        if (right > 0 && right > left) 
            generate(res, left, right - 1, s + ")");        
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        GenerateParentheses g = new GenerateParentheses();
        for (String s : g.generateParenthesis(3)) {
            System.out.println(s);
        }
    }

}

 

LeetCode - Generate Parentheses

原文:http://www.cnblogs.com/shuaiwhu/p/5060562.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!