zoukankan      html  css  js  c++  java
  • [LeetCode] 22. Generate Parentheses(括号生成器)

    Description

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
    n 对括号,写一个函数生成所有有效的括号对

    Examples

    Example 1

    Input: n = 3
    Output: ["((()))","(()())","(())()","()(())","()()()"]
    

    Example 2

    Input: n = 1
    Output: ["()"]
    

    Constraints

    • 1 <= n <= 8

    Solution

    在回溯类的题目中,此题属于排列树。考虑到本题要求括号对是有效的,自然一开始往里添加的时候,就要先添加左括号,然后如果右括号数量不够,尝试在其中添加右括号,代码如下:

    class Solution {
        private val result = arrayListOf<String>()
    
        fun generateParenthesis(n: Int): List<String> {
            backtrack("", 0, 0, n)
            return result
        }
    
        private fun backtrack(cur: String, left: Int, right: Int, total: Int) {
            if (cur.length == total * 2) {
                result.add(cur)
                return
            }
            if (left < total) {
                backtrack("$cur(", left + 1, right, total)
            }
            if (right < left) {
                backtrack("$cur)", left, right + 1, total)
            }
        }
    }
    
  • 相关阅读:
    现代软件工程 第一周博客作业
    最后一周总结
    阅读后感
    软件工程作业个人项目——csdn app分析
    第二次结对编程
    软件工程作业二
    软件工程作业一
    ASE 课程最后小结
    阅读后感
    Judy Beta 第五天
  • 原文地址:https://www.cnblogs.com/zhongju/p/13889102.html
Copyright © 2011-2022 走看看