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]:

扫描二维码关注公众号,回复: 2433145 查看本文章

[思维问题]:

不知道括号的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

猜你喜欢

转载自www.cnblogs.com/immiao0319/p/9383390.html
今日推荐