zoukankan      html  css  js  c++  java
  • Generate Parentheses

    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 class Solution {
        /**
         * 也可以参考http://blog.csdn.net/u011095253/article/details/9158429的第二种方法
        **/
        public ArrayList<String> generateParenthesis(int n) {
            if (n<=0) {
                return new ArrayList<String>();
            }
            if (n==1) {
                ArrayList<String> ret = new ArrayList<String>();
                ret.add("()");
                return ret;
            }
            ArrayList<String> ret = generateParenthesis(n-1);
            HashSet<String> ret2 = new HashSet<String>();
            for (String temp : ret) {
                ret2.add("("+temp+")");
                ret2.add("()"+temp);
                ret2.add(temp+"()");
                //fix result (())(())
                for (int j=0;j<temp.length();j++) {
                    if (temp.charAt(j) == '(') {
                        String fix = temp.substring(0, j+1) + "()" + temp.substring(j+1);
                        ret2.add(fix);
                    }
                }
            }
            ret.clear();
            for (String s:ret2) {
                ret.add(s);
            }
    
            return ret;
        }
    }
  • 相关阅读:
    luogu1210 回文检测
    luogu2420 让我们异或吧
    luogu4151 最大XOR和路径
    线性基
    博弈论(扯淡)
    矩阵求逆 模板
    luogu2513 逆序对数列
    洛谷4316 绿豆蛙的归宿(DAG递推/概率dp)
    1898: [Zjoi2005]Swamp 沼泽鳄鱼
    矩阵
  • 原文地址:https://www.cnblogs.com/23lalala/p/3507120.html
Copyright © 2011-2022 走看看