zoukankan      html  css  js  c++  java
  • 22. 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:

    [
      "((()))",
      "(()())",
      "(())()",
      "()(())",
      "()()()"
    ]

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    不知道括号的backtracing怎么写:定义open和close整数,分open < max 和close < open两个阶段来回溯

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [一句话思路]:

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    open close都是括号个数,int 直接加一就行了

    [复杂度]:Time complexity: O() Space complexity: O(n)

    [算法思想:迭代/递归/分治/贪心]:迭代

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> result = new ArrayList<String>();
            if (n <= 0) return result;
            generateParenthesisHelper(0, 0, new String(), result, n);
            return result;
        }
        
        public void generateParenthesisHelper(int open, int close, String item, List<String> result, int max) {
            //add to result
            if (item.length() >= 2 * max) {
                result.add(item);
                return ;
            }
            
            //backtracing in 2 stages
            if (open < max)  generateParenthesisHelper(open + 1, close, item + '(', result, max);
            if (close < open) generateParenthesisHelper(open, close + 1, item + ')', result, max);
        }
    }
    View Code
  • 相关阅读:
    python3线程介绍01(如何启动和调用线程)
    CentOS7 设置静态 ip
    png2ico
    Thunderbird 配置 QQ mail
    memcached 开机启动 (Ubuntu)
    CentOS7 docker 安装的 container-selinux 问题及解决
    YAML 的基本语法
    docker 的脚本化安装和使用
    解决Windows下 “setup.py build” 时出现错误 ” error: Unable to find vcvarsall.bat”
    Electric Fence
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9383390.html
Copyright © 2011-2022 走看看