天天看点

LeetCode 22. Generate Parentheses22. Generate Parentheses

题目来源:https://leetcode.com/problems/generate-parentheses/

问题描述

22. Generate Parentheses

Medium

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对括号组成的所有合法括号序列

------------------------------------------------------------

思路

动态规划。n对括号的序列可以由(n-1)对括号的所有空隙中插入一对括号得到,再用set去重即可。例如,要求n=3, 从n=2的结果[“()()”, “(())”]出发:

.()() -> ()()()

(.)() -> (())()

().() -> ()()()

()(.) -> ()(())

()(). -> ()()()

.(()) -> ()(())

(.()) -> (()())

((.)) -> ((()))

(().) -> (()())

(()). -> (())()

------------------------------------------------------------

代码

class Solution {
    public List<String> generateParenthesis(int n) {
        if (n == 0)
        {
            return new LinkedList<String>(){
                {
                    add("");
                }
            };
        }
        Set<String> ret = new HashSet<String>() {
            {
                add("");
            }
        };
        int i = 0, j = 0, len = 0;
        for (i=1; i<=n; i++)
        {
            Set<String> pret = new HashSet<String>(ret);
            ret.clear();
            for (String str: pret)
            {
                len = str.length();
                for (j=0; j<len; j++)
                {
                    String nstr = str.substring(0, j) + "()" + str.substring(j);
                    ret.add(nstr);
                }
                ret.add(str + "()");
            }
        }
        return new LinkedList<String>(ret);
    }
}