LeetCode #22 Generate Parentheses (M)

[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;
    }         
}

 

posted on 2015-10-10 00:31  张惬意  阅读(155)  评论(0编辑  收藏  举报