首页 > 其他 > 详细

LeetCode #22 Generate Parentheses (M)

时间:2015-10-10 01:32:42      阅读:236      评论:0      收藏:0      [点我收藏+]

[Problem]

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:

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

 

[Analysis]

这题的思路大部分是枚举解集,大概类似二叉集合树的结构,左分支就是添加左括号,右分支添加右括号,直至不能添加括号结束或者已经添加了n对括号得到一个解。

在网上有另一种非常精巧的思路,是通过观察组合的规律得来的:

n = 0,解集为:""

n = 1,解集为:"()"

n = 2,解集为:"(())", "()()", ""

n = 3,解集为:"((()))", "(()())", "(())()", "()(())", "()()()"

n = N的解比n = N-1的解要多一个括号,而由N-1的解得到N的解是有规律的:

假设S(N)表示n = N时的解集

S(2) = "([S(1)])[S(0)]" + "([S(0)])[S(1)]"

S(N) = "([S(0)])[S(N - 1)]" + "([S(1)])[S(N - 2)]" + ... + "([S(N - 1)])[S(0)]"

注意这些解是不会重复的。

 

[Solution]

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

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        if (n == 0) {
            result.add("");
            return result;
        }        
        
        for (int i = 0; i < n; i++) {
            List<String> temp1 = generateParenthesis(i);
            List<String> temp2 = generateParenthesis(n - 1 - i);

            for (String s1: temp1) {
                for (String s2: temp2) {
                    result.add("(" + s1 + ")" + s2);
                }
            }            
        }
        
        return result;
    }         
}

 

LeetCode #22 Generate Parentheses (M)

原文:http://www.cnblogs.com/zhangqieyi/p/4865575.html

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