zoukankan      html  css  js  c++  java
  • 22.括号生成

    题目:

    给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
    
    例如,给出 n = 3,生成结果为:
    
    [
      "((()))",
      "(()())",
      "(())()",
      "()(())",
      "()()()"
    ]
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/generate-parentheses

    分析:

    题目刚拿到的时候确实没有思路,看了一下LeetCode的题解,注意到最后方法三的闭合数解法。

    这里官方是采用了一个遍历回溯的思路,保证每一个添加的集合都是有效的,如何保证有效呢?当然是左右对称,那么就可以得到如下的代码:

    public static List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        if (n == 0) {
            //结束回溯的关键
            result.add("");
        } else {
            for (int c = 0; c < n; ++c) {
                //遍历得到每一个需要添加的左右对称组合
                for (String left : generateParenthesis(c)) {
                    for (String right : generateParenthesis(n - 1 - c)) {
                        //保证添加的左侧为对称的,右侧遍历而来,肯定也是对称的
                        result.add("(" + left + ")" + right);
                    }
                }
            }
        }
        return result;
    }
    View Code
  • 相关阅读:
    CTF SQL注入知识点
    Rot13加密算法
    LFU缓存
    Redability
    快排
    更新卡片的zIndex
    webshell文件下载器
    [转]背包九讲
    hihocoder第196周
    Python import容易犯的一个错误
  • 原文地址:https://www.cnblogs.com/doona-jazen/p/12004598.html
Copyright © 2011-2022 走看看